在左连接中使用group_concat

时间:2015-11-24 20:02:15

标签: mysql join group-concat

我想我可能会试图对我的代码过于狡猾:p 我试图将2个表连接在一起,一个用1行,另一个用几个。但我只想为第一个表和另一个表返回一行。所以我试图使用GROUP_CONCAT将我的联接更改为单行,如下所示:

col 1 || col 2 || col 3 (linked)
----------------------------------
  23  ||  Data ||  data, data, data

然后我可以解决这个问题。

我认为问题是,如果你有什么要加入,这是否真的有效?如果我没有加入行,那么它们似乎被忽略了?如果我在子查询中这样做,它返回null?

这是我的疑问

子查询

SELECT * FROM wp_fishy_posts p 
    LEFT JOIN (SELECT GROUP_CONCAT(i.path,',') AS linked_images,l.postID as link_id 
        FROM wp_fishy_images i 
        LEFT JOIN wp_fishy_images_post_link l ON l.imageID=i.ID) AS l ON l.link_id=p.ID
    WHERE p.post_type='image'

加入行时返回null?

SELECT GROUP_CONCAT(i.path,',') AS linked_images,p.*
FROM wp_fishy_posts p
(SELECT i.path,l.postID as link_id 
    FROM wp_fishy_images i 
    LEFT JOIN wp_fishy_images_post_link l ON l.imageID=i.ID) AS l ON l.link_id=p.ID
WHERE p.post_type='image'

不确定我做错了什么? :S先谢谢!

1 个答案:

答案 0 :(得分:1)

子查询中需要group by

SELECT *
FROM wp_fishy_posts p LEFT JOIN
     (SELECT GROUP_CONCAT(i.path,',') AS linked_images, l.postID as link_id 
      FROM wp_fishy_images i LEFT JOIN
           wp_fishy_images_post_link l
           ON l.imageID = i.ID
      GROUP BY l.postId
------^
     ) l
     ON l.link_id = p.ID
WHERE p.post_type = 'image';