在左连接中使用 group_concat
Using group_concat in left join
我想我的代码可能太狡猾了:p
我正在尝试 link 2 tables 一个与 1 行和另一个与几个。但我只想 return 一行用于第一个 table 和另一行。所以我正在尝试使用 GROUP_CONCAT
将我的连接更改为单行,如下所示:
col 1 || col 2 || col 3 (linked)
----------------------------------
23 || Data || data, data, data
那以后我可以把它拆开。
我认为问题是,这是否只有在您有加入的情况下才真正有效?如果我没有加入行,那么它们似乎被忽略了?如果我在子查询中这样做 returns 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'
Returns 合并行时为空?
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';
我想我的代码可能太狡猾了:p
我正在尝试 link 2 tables 一个与 1 行和另一个与几个。但我只想 return 一行用于第一个 table 和另一行。所以我正在尝试使用 GROUP_CONCAT
将我的连接更改为单行,如下所示:
col 1 || col 2 || col 3 (linked)
----------------------------------
23 || Data || data, data, data
那以后我可以把它拆开。
我认为问题是,这是否只有在您有加入的情况下才真正有效?如果我没有加入行,那么它们似乎被忽略了?如果我在子查询中这样做 returns 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'
Returns 合并行时为空?
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';