【发布时间】:2023-02-25 05:12:02
【问题描述】:
我的目标是获得一个结果,它将输出所有练习条目,一个相关视频,然后是所有关联标签的连接字符串(其中标签是一个表,tag_linkage 是标签与练习的关系)。
理想的最终结果:
My Exercise Name, Somepath/video.mp4, TagName1|TagName2|TagName3
Another Exercise Name, Somepath/video.mp4, TagName2|TagName5|TagName6
and so on...
我有这个结构:
CREATE TABLE `exercises` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
`video_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `videos` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`filename` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `tags` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `tag_linkage` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`exercise_id` int(11) DEFAULT NULL,
`tag_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
)
到目前为止,这是我的查询:
SELECT
exercises.name AS Exercise,
videos.filename AS VideoName,
tags.name as Tag,
FROM exercises
INNER JOIN tag_linkage AS tl ON exercises.id = tl.exercise_id
INNER JOIN tags ON tags.id = tl.tag_id
LEFT JOIN videos
ON exercises.video_id = videos.id
ORDER BY exercises.id
LIMIT 20000
OFFSET 0;
标签上的连接是我卡住的地方。 tag_linkage 表有一个 exercise_id 和一个 tag_id。我需要能够使用 exercises.id 作为 tag_linkage.exercise_id 的连接,但从另一个表返回 tag.name,但我不知道如何处理它。上面的当前查询给我 Tag 作为结果中的一列,但每个标签都是一个新行:
My Exercise Name, Somepath/video.mp4, TagName1
My Exercise Name, Somepath/video.mp4, TagName2
My Exercise Name, Somepath/video.mp4, TagName3
Another Exercise Name, Somepath/video.mp4, TagName1
Another Exercise Name, Somepath/video.mp4, TagName3
Another Exercise Name, Somepath/video.mp4, TagName5
and so on...
我想删除重复的行并将标签连接成 1 列。
编辑:想通了。
SELECT
exercises.name as Exercise,
videos.filename AS VideoName,
GROUP_CONCAT(DISTINCT(tags.name) separator ', ') Tags,
FROM exercises
LEFT JOIN videos
ON exercises.video_id = videos.id
JOIN tag_linkage ON exercises.id = tag_linkage.exercise_id
JOIN tags ON tags.id = tag_linkage.tag_id
GROUP BY exercises.name
LIMIT 1000
OFFSET 0;
【问题讨论】:
-
注意:如果您有一个同时包含 INNER 和 OUTER JOINS 的查询,那么所有 INNER 都应该在 OUTER 之前。如果不可能,那么所有这些都应该是外部的。