我的目标是得到一个结果,其中它将输出所有练习条目,以及一个相关视频,然后是所有关联标签的连接字符串(其中标签是一个表,标签链接是标签与练习的关联方式)。
理想的最终结果:
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从另一个表返回www.example.com,但我不知道如何处理它。上面的当前查询将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;
2条答案
按热度按时间643ylb081#
您需要单独连接标签
3pmvbmvn2#
我想明白了: