gpt4 book ai didi

mysql - GROUP BY、GROUP_CONCAT、CONCAT 以及如何选择

转载 作者:行者123 更新时间:2023-11-29 14:33:56 24 4
gpt4 key购买 nike

我有三张 table

objects     id, field1, field2, ...
groups id, title, color
group_ref oid, gid

因此每个对象都可以分为 n 组。

我想显示一个对象列表,该列表的一个字段是对象所在的组。所以这是我想到的:

SELECT o.id,
CONCAT_WS("||", GROUP_CONCAT(gx.gid separator "|"), GROUP_CONCAT(gr.title, "#", gr.color separator "|")) AS groups
FROM objects AS o
LEFT JOIN group_ref AS gx ON o.id = gx.oid
LEFT JOIN groups AS gr ON gx.gid = gr.id
WHERE 1
GROUP BY o.id

这确实有效,我可以从(连接的)组字段中创建所需的界面。

问题是:如何选择仅属于一个特定组的对象(例如 gid=4)?

这只能得到部分结果:

WHERE gr.id = 4

HAVING gr.id = 4

非常感谢任何帮助! (也许对于 concat 也有一种更优雅的方式)

最佳答案

如果我理解正确的话,您想要获取组 4 中的所有对象以及这些对象所在的所有组。您想要在 group_ref 表上 JOIN 两次,一次用于过滤(常规 JOIN),一次用于获取相关组(左连接)。

SELECT o.id,
CONCAT_WS("||", GROUP_CONCAT(gx.gid separator "|"),
GROUP_CONCAT(gr.title, "#", gr.color separator "|")) AS groups
FROM objects AS o
JOIN group_ref AS gfilter ON o.id = gfilter.oid AND gfilter.gid=4
LEFT JOIN group_ref AS gx ON o.id = gx.oid
LEFT JOIN groups AS gr ON gx.gid = gr.id
WHERE 1
GROUP BY o.id

关于mysql - GROUP BY、GROUP_CONCAT、CONCAT 以及如何选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9457077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com