自定义连接查询从3表获取记录

时间:2015-03-23 13:35:36

标签: php mysql database

我在mysql数据库中有3个表,如下面的

表1:视频

id    name
1     one
2     two
3     three

表2:标签

id    name
1     stage=test
2     age=under18

表3:tags_to_items 其中tags_id = tags.iditem_id = videos.id

tag_id    item_id
1         1
2         2
2         1
1         3 

此处item_id 1有2个标签。 我想从videos表中选择tag_id=1tag_id=2的所有记录。所以输出应该是video.id=1

请提前帮助我这样做。

3 个答案:

答案 0 :(得分:0)

您真的不需要视频或加入任何查询。到目前为止做你需要的:

SELECT item_id as VIDEO_ID 
   SUM(CASE WHEN tag_id = 1 THEN 1 ELSE 0 END) as tag_1,
   SUM(CASE WHEN tag_id = 2 THEN 1 ELSE 0 END) as tag_2
FROM tags_to items
WHERE tag_id = 1 or tag_id = 2
GROUP BY VIDEO_ID
HAVING tag_1>0 AND tag_2>0

答案 1 :(得分:0)

SELECT * FROM videos WHERE id IN (SELECT item_id FROM tags_to_items WHERE tag_id IN (1,2) )

答案 2 :(得分:0)

你可以这样做:

            SELECT t1.tag_id, t1.item_id, t2.name AS tagName, t3.name AS videoName FROM tags_to_items AS t1

            LEFT JOIN tags AS t2 ON t1.tag_id=t2.id

            LEFT JOIN videos AS t3 ON t1.item_id=t3.id

            WHERE t1.tag_id IN (1,2)