Reputation: 8703
I have two SQL tables:
items table
item_id name timestamp
--------------------------------------------
a apple 2014-01-01
b banana 2014-01-06
c tomato 2013-12-25
d chicken 2014-01-23
e cheese 2014-01-02
f carrot 2014-01-16
items_to_categories table
cat_id item_id
--------------------------------------------
1 a
5 c
2 e
3 a
4 f
5 d
5 b
5 a
Knowing cat_id
(eg 5), I need to get 2 latest items (based on the timestamp
) that belongs to that cat_id
.
If I first get 2 rows from items_to_categories table:
SELECT item_id FROM items_to_categories WHERE cat_id = 5 LIMIT 2;
>> returns 'c' and 'd'
And then use returned items ids to query items table, I am not making sure returned items will be the latest ones (order by timestamp
).
The ideal result what I need to get selecting 2 latest items by cat_id
(eg 5) would be:
d chicken 2014-01-23
b banana 2014-01-06
Upvotes: 2
Views: 106
Reputation: 93
Try this using join to get the required result
SELECT a . *
FROM items a
INNER JOIN items_to_categories b ON a.item_id = b.cat_id
ORDER BY a.timestamp DESC LIMIT 2
Upvotes: 0
Reputation:
You can try something like this
SELECT
items.item_id
items.item,
items.item_timestamp
FROM
items_to_categories
INNER JOIN items ON items_to_categories.item_id = items.item_id
WHERE
items_to_categories.cat_id = 5
ORDER BY items.item_timestamp desc
limit 2
By the way, timestamp is a reserved word, you really should avoid using it for a field name
Hope it will helps
Upvotes: 1
Reputation: 1007
SELECT top 2 I.item_id, I.name, I.timestamp
FROM items I
JOIN items_to_categories IC ON I.item_id = IC.item_id
WHERE IC.cat_id in (Select top 1 from items_to_categories order by timestamp desc)
ORDER BY I.timestamp DESC
Upvotes: 1
Reputation: 15603
SELECT t1.item_id, t1.name, t1.timestamp
FROM items t1
LEFT JOIN items_to_categories t2 ON t1.item_id = t2.item_id
WHERE cat_id = 5
ORDER BY t1.timestamp DESC
LIMIT 2;
Use above query.
Upvotes: 2