I'm currently having a strange problem with a complex sql code. Here is the schema:
CREATE TABLE category (
category_id SERIAL PRIMARY KEY,
cat_name CHARACTER VARYING(255)
);
CREATE TABLE items (
item_id SERIAL PRIMARY KEY,
category_id INTEGER NOT NULL,
item_name CHARACTER VARYING(255),
CONSTRAINT item_category_id_fk FOREIGN KEY(category_id) REFERENCES category(category_id) ON DELETE RESTRICT
);
CREATE TABLE item_prices (
price_id SERIAL PRIMARY KEY,
item_id INTEGER NOT NULL,
price numeric,
CONSTRAINT item_prices_item_id_fk FOREIGN KEY(item_id) REFERENCES items(item_id) ON DELETE RESTRICT
);
INSERT INTO category(cat_name) VALUES('Category 1');
INSERT INTO category(cat_name) VALUES('Category 2');
INSERT INTO category(cat_name) VALUES('Category 3');
INSERT INTO items(category_id, item_name) VALUES(1, 'item 1');
INSERT INTO items(category_id, item_name) VALUES(1, 'item 2');
INSERT INTO items(category_id, item_name) VALUES(1, 'item 3');
INSERT INTO items(category_id, item_name) VALUES(1, 'item 4');
INSERT INTO item_prices(item_id, price) VALUES(1, '24.10');
INSERT INTO item_prices(item_id, price) VALUES(1, '26.0');
INSERT INTO item_prices(item_id, price) VALUES(1, '35.24');
INSERT INTO item_prices(item_id, price) VALUES(2, '46.10');
INSERT INTO item_prices(item_id, price) VALUES(2, '30.0');
INSERT INTO item_prices(item_id, price) VALUES(2, '86.24');
INSERT INTO item_prices(item_id, price) VALUES(3, '94.0');
INSERT INTO item_prices(item_id, price) VALUES(3, '70.24');
INSERT INTO item_prices(item_id, price) VALUES(4, '46.10');
INSERT INTO item_prices(item_id, price) VALUES(4, '30.0');
INSERT INTO item_prices(item_id, price) VALUES(4, '86.24');
Now the problem here is, I need to get an item, its category and the latest inserted item_price.
My current query looks like this:
SELECT
category.*,
items.*,
f.price
FROM items
LEFT JOIN category ON category.category_id = items.category_id
LEFT JOIN (
SELECT
price_id,
item_id,
price
FROM item_prices
ORDER BY price_id DESC
LIMIT 1
) AS f ON f.item_id = items.item_id
WHERE items.item_id = 1
Unfortunately, the price column is returned as NULL. What I don't understand is why? The join in the query works just fine if you execute it stand-alone.
SQLFiddle with the complex query:
http://sqlfiddle.com/#!1/33888/2
SQLFiddle with the the join solo:
http://sqlfiddle.com/#!1/33888/5