gpt4 book ai didi

mysql - 来自使用 GROUP_CONCAT() 打包的 Tri-INNER JOIN-Relation 的重复值

转载 作者:太空宇宙 更新时间:2023-11-03 11:32:21 24 4
gpt4 key购买 nike

我应该得到以下行

[id -              gamma             -              omega            ]
[1 - Gamma1, Gamma2, Gamma3, Gamma4 - Omega1, Omega2, Omega3, Omega4]

但我得到的结果显示在 SQLFiddle

如果我删除了 SET 并保留了它的 GROUP_CONCAT(),它会正常工作。

为什么关系会相互作用并产生重复值?

SQL:

SELECT a.id, 
GROUP_CONCAT(g.name) AS gamma,
GROUP_CONCAT(o.name) AS omega
FROM alpha a

#SET A.O.
INNER JOIN alpha_omega ao ON ao.alpha_id = a.id
INNER JOIN omega o ON o.id = ao.omega_id

#SET A.G.
INNER JOIN alpha_gamma ag ON ag.alpha_id = a.id
INNER JOIN gamma g ON g.id = ag.gamma_id

WHERE a.id = 1
GROUP BY a.id

最佳答案

可能是正确的连接(不使用 GROUP_CONCAT(DISTINCT ...)):

SELECT a.id, GROUP_CONCAT(o.name) AS omega  
FROM alpha a
JOIN delta d ON d.alpha_id = a.id
JOIN omega o ON o.id = d.omega_id
GROUP BY a.id
UNION ALL
SELECT a.id, GROUP_CONCAT(g.name) AS gamma
FROM alpha a
JOIN beta b ON b.alpha_id = a.id
JOIN gamma g ON g.id = b.gamma_id
GROUP BY a.id;

在一行内:

SELECT id, MIN(gamma) AS gamma, MIN(omega) AS omega
FROM (
SELECT a.id, NULL AS gamma, GROUP_CONCAT(o.name ORDER BY o.name) AS omega
FROM alpha a
JOIN delta d ON d.alpha_id = a.id
JOIN omega o ON o.id = d.omega_id
GROUP BY a.id
UNION ALL
SELECT a.id, GROUP_CONCAT(g.name ORDER BY g.name) AS gamma, NULL
FROM alpha a
JOIN beta b ON b.alpha_id = a.id
JOIN gamma g ON g.id = b.gamma_id
GROUP BY a.id
) sub
GROUP BY id;

SQL Fiddle Demo

关于mysql - 来自使用 GROUP_CONCAT() 打包的 Tri-INNER JOIN-Relation 的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48751162/

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