简体   繁体   English

自定义联接查询以从3个表中获取记录

[英]custom join query to get record from 3 table

I have 3 table in mysql database like following 我在mysql数据库中有3个表,如下所示

table 1 : videos 表1:视频

id    name
1     one
2     two
3     three

table 2: tags 表2:标签

id    name
1     stage=test
2     age=under18

table 3 : tags_to_items where tags_id = tags.id and item_id = videos.id 表3:tags_to_items ,其中tags_id = tags.iditem_id = videos.id

tag_id    item_id
1         1
2         2
2         1
1         3 

Here item_id 1 has 2 tags. 这里item_id 1有2个标签。 I want to select all the records from videos table where tag_id=1 and tag_id=2 . 我想选择所有记录videos表,其中tag_id=1tag_id=2 So output should be video.id=1 . 因此输出应为video.id=1

Please help me to do like that, thanks in advance. 请先帮助我做到这一点,谢谢。

You really don't need any query from videos or join. 您真的不需要来自视频的任何查询或加入。 Just do what you need so far: 只需执行到目前为止所需的操作即可:

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
SELECT * FROM videos WHERE id IN (SELECT item_id FROM tags_to_items WHERE tag_id IN (1,2) )

You can do like this: 您可以这样:

            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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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