我想我可能想对我的代码偷偷摸摸: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预先感谢!
最佳答案
您需要在子查询中使用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';
关于mysql - 在左联接中使用group_concat,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33902749/