[英]Advice on Optimizing Joins Query
I have 3 tables : videos
, categories
, video_categories
. 我有3个表格: videos
, categories
, video_categories
。
In videos
, I have id, title, and other fields. 在videos
,我具有ID,标题和其他字段。 In categories
, I have id and name. 在categories
,我有ID和名称。 In video_categories
, I have id, video_id, and category_id. 在video_categories
,我有id,video_id和category_id。
One video can have multiple categories. 一个视频可以具有多个类别。 So the video_categories table will be something like this. 因此video_categories表将是这样的。
id video_id category_id
1 1 1
2 1 2
3 1 3
If I want to have a list of videos and display their categories, which would be preferred? 如果我想要一个视频列表并显示其类别,哪个会是首选?
Via PHP, call 1 query to get all videos, then loop on that to query to get each video's categories, and another query to get the category name. 通过PHP,调用1查询以获取所有视频,然后在其上循环查询以获取每个视频的类别,并调用另一个查询以获取类别名称。 This will be really slow if the table is huge, right? 如果桌子很大,这真的很慢,对吗?
Via MySQL joins (need help on this). 通过MySQL加入(需要帮助)。 If I left join videos to video_categories, there will be 3 results of the same video_id. 如果我将加入视频的内容留给video_categories,则将有3个结果相同的video_id。 I can use GROUP BY or SELECT DISTINCT to get unique result, but how can I now get the categories' names? 我可以使用GROUP BY或SELECT DISTINCT来获得唯一的结果,但是现在如何获得类别的名称呢?
My expected result will be something like this: 我的预期结果将是这样的:
id title categories
1 Video1 pop, rock, jazz
For option 2, use GROUP_CONCAT
. 对于选项2,使用GROUP_CONCAT
。 It will be ok 一切都会安好的
SELECT v.id, v.title, GROUP_CONCAT(c.name)
FROM videos v
INNER JOIN video_categories vc ON vc.video_id = v.id
INNER JOIN categories c ON vc.category_id = c.id
GROUP BY v.id, v.title
For Group_Concat()
function ,
is the default separator. 对于Group_Concat()
函数,
是默认的分隔符。 That's why I don't use it here. 这就是为什么我在这里不使用它。
Guessing the names of your other columns.. 猜测其他列的名称。
SELECT v.video_id, v.title, GROUP_CONCAT(c.category_name SEPARATOR ', ')
FROM videos v
LEFT JOIN video_categories vc ON vc.video_id = v.video_id
LEFT JOIN categories c ON c.category_id = vc.category_id
GROUP BY v.video_id, v.title
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.