GROUP BY,GROUP_CONCAT,CONCAT以及如何选择

时间:2012-02-26 20:57:19

标签: mysql

我有三张桌子

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 thingy)

3 个答案:

答案 0 :(得分:1)

如果我理解正确,你想获得第4组中的所有对象以及那些对象所在的所有组。你想在group_ref表上加入两次,一次过滤(常规JOIN)和一次得到相关小组(LEFT 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

答案 1 :(得分:0)

这有用吗?

WHERE gr.id = 4
GROUP BY o.id
HAVING COUNT(*) = 1

答案 2 :(得分:0)

这应显示仅在一个组中的对象:

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
GROUP BY o.id
HAVING COUNT(DISTINCT gx.gid) = 1