我有两个SQL表:
项表
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 表
cat_id item_id
--------------------------------------------
1 a
5 c
2 e
3 a
4 f
5 d
5 b
5 a
了解cat_id
(例如5 ),我需要获得属于timestamp
的2个最新项目(基于cat_id
)。
如果我首先从 items_to_categories 表中获得2行:
SELECT item_id FROM items_to_categories WHERE cat_id = 5 LIMIT 2;
>> returns 'c' and 'd'
然后使用返回的项ID来查询项表,我不确定返回的项目是否为最新项目(按timestamp
排序)。
我需要通过cat_id
(例如5 )选择2个最新项目的理想结果是:
d chicken 2014-01-23
b banana 2014-01-06
答案 0 :(得分:2)
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;
使用以上查询。
答案 1 :(得分:1)
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
答案 2 :(得分:1)
您可以尝试这样的事情
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
顺便说一下,时间戳是一个保留字,你真的应该避免将它用作字段名
希望它会有所帮助
答案 3 :(得分:0)
尝试使用join来获取所需的结果
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