简体   繁体   English

从表中选择与其他表记录匹配的行

[英]Select rows from a table matching other table records

I have two SQL tables: 我有两个SQL表:

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 items_to_categories

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 . 知道cat_id例如5 )后,我需要获取2个属于该cat_id最新项(基于timestamp )。

If I first get 2 rows from items_to_categories table: 如果我首先从items_to_categories表中获得2行:

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 ). 然后使用返回的项目ID来查询项目表,但我不确定返回的项目将是最新的(按timestamp排序)。

The ideal result what I need to get selecting 2 latest items by cat_id ( eg 5 ) would be: 我需要通过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;

Use above query. 使用上面的查询。

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

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 希望这会有所帮助

Try this using join to get the required result 尝试使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM