数据库
首页 > 数据库> > mysql-通过获取所有表结果将每行concat分组

mysql-通过获取所有表结果将每行concat分组

作者:互联网

对于我的搜索索引,我需要创建一个sql以获取serval表结果.

例如,我有下表.

>标签(在此表中,我获得了所有标签)
> video_tags(在此表中,我获得与标签ID相关的video_id)
>视频(所有视频)

当我想获取带有标签的电影时,请使用以下查询;

SELECT 
  videos.id,
  videos.id AS video_id,
  videos.video_title AS video_title,
  Group_Concat(DISTINCT t.tag_name SEPARATOR '|') AS tag_names 
FROM videos
JOIN video_tags AS vt ON vt.video_id = videos.id 
JOIN tags AS t ON t.tag_id = vt.tag_id 
WHERE videos.id = '10'

这对我来说很完美.

现在,我需要像这样从表中获取所有结果;

SELECT 
  videos.id,
  videos.id AS video_id,
  videos.video_title AS video_title,
  Group_Concat(DISTINCT t.tag_name SEPARATOR '|') AS tag_names 
FROM videos
JOIN video_tags AS vt ON vt.video_id = videos.id 
JOIN tags AS t ON t.tag_id = vt.tag_id 
WHERE videos.id <=( SELECT max_doc_id FROM sph_counter WHERE counter_id=1 )

我在这里面临的问题是如何使用group_concat函数.它结合了所有行
分成一行(我能理解).我的问题是,我该如何使用group_concat函数将所有标记结果放入单个字段,但将PER行放入.

例如现在结果

id | video_id | video_title | tag_names
 1       1      title of id1   all tag_names from tags

我想要的是

 id | video_id | video_title | tag_names
 1       1      title of id1   tags fort this row 
 2       2      title of id2   tags fort this row

解决方法:

SELECT videos.id,
       videos.id AS video_id,
       videos.video_title AS video_title,
       GROUP_CONCAT(DISTINCT t.tag_name SEPARATOR '|') AS tag_names 
FROM   videos
JOIN   video_tags AS vt
ON     vt.video_id = videos.id 
JOIN   tags AS t
ON     t.tag_id = vt.tag_id 
WHERE  videos.id <=
       (
       SELECT  max_doc_id
       FROM    sph_counter
       WHERE   counter_id = 1
       )
GROUP BY
       videos.id

标签:distinct,group-concat,sql,mysql
来源: https://codeday.me/bug/20191030/1967426.html