你好我有GROUP_CONCAT有多个LEFT JOIN的问题。
我有保存数据的主表connectors
,但由于mysql表不能保存数组,我将它们存储在不同的表modules
,subassemblies
中,并且数组中的每个元素都有自己的行。当这些数组的长度相同时,我的查询工作正常,但是当我从模块表中获取3行但只有subassemblies
表中的一行时,我得错了结果。
示例结果:
id modulepath subassemblypath
1 mp1|mp2|mp3 sp1|sp1|sp1 my result
1 mp1|mp2|mp3 sp1 expected result
连接器表:
id data
1 lorem
2 ipsum
3 data
模块表:
id cid modulepath
28 1 mp1
29 1 mp2
36 1 mp3
56 3 mp4
85 2 mp5
子装配表:
id cid subassemblypath
26 1 sp1
31 2 sp2
48 2 sp3
56 3 sp4
我的疑问:
SELECT
c.*,
GROUP_CONCAT(m.modulepath SEPARATOR "|") AS modulepath,
GROUP_CONCAT(s.subassemblypath SEPARATOR "|") AS subassemblypath
FROM connectors c
LEFT JOIN modules m ON m.cid = c.id
LEFT JOIN subassemblies s ON s.cid = c.id
GROUP BY c.id;
答案 0 :(得分:0)
尝试将查询拆分为两个,然后执行连接
SELECT c.*, t2.modulepath, t1.subassemblypath
FROM connectors c
JOIN (
SELECT
s.cid,
GROUP_CONCAT(s.subassemblypath SEPARATOR "|") AS subassemblypath
FROM subassemblies s
GROUP BY s.cid
) t1 ON c.id = t1.cid
JOIN
(
SELECT
m.cid,
GROUP_CONCAT(m.modulepath SEPARATOR "|") AS modulepath
FROM modules m
GROUP BY m.cid
) t2 ON c.id = t2.cid