获取所有表结果的每行Group_concat

时间:2013-09-25 18:53:17

标签: mysql sql distinct group-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行。

e.g。结果现在

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

1 个答案:

答案 0 :(得分:4)

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