[英]MySQL: why does GROUP_CONCAT lose rows in my multiple join query?
I'm trying to fetch all the rows from table_m which also have an index in table_mi and I'm expecting to get 2 rows as a result (with m.id=3 and m.id=9) - but if I add GROUP_CONCAT to my select then I only get one row returned. 我正在尝试从table_m中获取所有行,其中table_mi中也有一个索引,因此我希望得到2行(m.id = 3和m.id = 9)-但是如果我添加GROUP_CONCAT按我的选择,那么我只会返回一行。 Am I having a misshap somewhere within those joins of mine?
我的那些联接中某处是否发生了事故?
Query: 查询:
SELECT
m.id,
m.name,
m.keyword,
IFNULL(GROUP_CONCAT(r.keyword),'TEST') AS restrictions
FROM
table_m AS m
INNER JOIN
table_mi as mi ON m.id=mi.m_id
LEFT JOIN
table_ri as ri ON m.id=ri.m_id
LEFT JOIN
table_r AS r ON ri.r_id=r.id
WHERE
(
m.id>0
AND m.active=1
AND mi.p_id=0
AND (mi.pa_id="11" OR (mi.pa_id=0 AND mi.id!=0))
AND mi.u_id=IF((SELECT id FROM table_mi WHERE p_id=0 AND pa_id="11" AND u_id="2")>0,"2",0)
) OR mi.id=0
ORDER BY
mi.priority;
This is what I'm getting as a result: 这就是我得到的结果:
ID NAME KEYWORD RESTRICTIONS 9 test_a key_a r_key_2,r_key_3,r_key_4
This is what I'm expecting: 这是我所期望的:
ID NAME KEYWORD RESTRICTIONS 9 test_a key_a r_key_2,r_key_3,r_key_4 3 test_b key_b TEST
Please see my full example with schema on sql fiddle: http://sqlfiddle.com/#!2/359d9/1 请参阅我在sql小提琴上具有架构的完整示例: http ://sqlfiddle.com/#!2/359d9/1
GROUP_CONCAT is an aggregate function. GROUP_CONCAT是一个聚合函数。 It will bring back a single row UNLESS you specify a GROUP BY clause (with any fields that are not in the GROUP BY being aggregate fields)
除非您指定GROUP BY子句,否则它将带回一行(除非GROUP BY子句中的任何字段均为聚合字段)
Before the ORDER BY add the following:- 在ORDER BY之前添加以下内容:
GROUP BY m.id, m.name, m.keyword
That said it looks like you might want to use CONCAT to join 2 values together rather than GROUP_CONCAT 也就是说,您似乎可能想使用CONCAT将2个值连接在一起,而不是GROUP_CONCAT
As an aside, your SQL might be easier to read if you eliminate the subselect. 顺便说一句,如果取消子选择,则SQL可能更易于阅读。 Assuming it is bringing back a single record then possibly as follows
假设它带回一条记录,则可能如下
SELECT
m.id,
m.name,
m.keyword,
IFNULL(GROUP_CONCAT(r.keyword),'TEST') AS restrictions
FROM
table_m AS m
INNER JOIN
table_mi as mi ON m.id=mi.m_id
LEFT JOIN
table_ri as ri ON m.id=ri.m_id
LEFT JOIN
table_r AS r ON ri.r_id=r.id
LEFT OUTER JOIN
table_mi AS mi2 ON mi2.p_id=0 AND mi2.pa_id="11" AND mi2.u_id="2"
WHERE
(
m.id>0
AND m.active=1
AND mi.p_id=0
AND (mi.pa_id="11" OR (mi.pa_id=0 AND mi.id!=0))
AND mi.u_id=IF(mi2.id >0,"2",0)
) OR mi.id=0
ORDER BY
mi.priority;
You do no need GROUP_CONCAT
to achieve what you want. 您不需要
GROUP_CONCAT
即可实现所需的功能。
Instead of : 代替 :
IFNULL(GROUP_CONCAT(r.keyword),'TEST') AS restrictions
use 采用
IFNULL(r.keyword,'TEST') AS restrictions
OR: 要么:
Keep the query as it is and add GROUP BY m.id
before ORDER BY
保持查询
GROUP BY m.id
在ORDER BY
之前添加GROUP BY m.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.