在不同的表中获取sql中的项目

时间:2013-10-02 09:27:21

标签: sql

我有以下表格..

items

ID | Title   |       Desc
67 | Title_1 |  Description_1
68 | Title_2 |  Description_2 

tag

ID |  Name
5  |  tag_1
7  | tag_2
22 | tag_3
23 | tag_4 

tag_ref

ID  | tagID   | itemID
1   | 5       | 68
2   | 7       | 67
3   | 5       | 67
4   | 23      | 68
5   | 22      | 68 

现在,我想选择与当前产品项目id = 67

具有相同tagID的所有项目

因为我想通过标签获取相关项目。

2 个答案:

答案 0 :(得分:0)

SELECT * FROM items JOIN item tag_ref on tag_ref.itemID = items.ID JOIN tag 
on tag.ID = tag_ref.tagID where item.ID = 67

答案 1 :(得分:0)

加入itemstag_ref,只返回子查询中存在tagID的项目,该子查询返回项目67的所有tagID:

SELECT items.*
FROM items
JOIN tag_ref as t on t.itemID = items.ID
WHERE t.tagID in (SELECT t2.tagID 
                  FROM tag_ref as t2
                  JOIN items as i2 on i2.ID = t2.itemID
                  WHERE i2.ID = 67)