[英]Select rows from a table matching other table records
我有兩個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 )后,我需要獲取2個屬於該cat_id
最新項(基於timestamp
)。
如果我首先從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
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;
使用上面的查詢。
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
您可以嘗試這樣的事情
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
順便說一句,時間戳是保留字,您確實應該避免將其用作字段名稱
希望這會有所幫助
嘗試使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.