我试图从不同的表中选择字段,并使用GROUP_CONCAT()对行进行分组。但是,如果GROUP_CONCAT()中的一个字段返回NULL,则所选的整个行将为NULL。
“成就”和“社交”中的字段允许为空。每个个人资料可以有多行成就和社交。
我尝试使用COALESCE更改查询,但没有成功:
SELECT p.UserId, p.Username, p.TextInfo, GROUP_CONCAT(DISTINCT CONCAT(COALESCE(a.Rank,''), '#', COALESCE(a.Tourney,''))) AS achievements, GROUP_CONCAT(DISTINCT CONCAT(COALESCE(s.platform,''),'#', COALESCE(s.URL,''))) AS socials from profile p INNER JOIN achievement a ON p.UserId = a.UserId INNER JOIN social s ON p.UserId = s.UserId WHERE p.Username LIKE '%uagib%'
预期结果:
<UserId> | <Username> | <TextInfo> | (multiple) <Rank>#<Tourney> | (multiple) <Platform>#<URL> |
答案 0 :(得分:0)
缺少分组依据子句
SELECT p.UserId, p.Username, p.TextInfo,
GROUP_CONCAT(DISTINCT CONCAT(COALESCE(a.Rank,''), '#', COALESCE(a.Tourney,''))) AS achievements,
GROUP_CONCAT(DISTINCT CONCAT(COALESCE(s.platform,''),'#', COALESCE(s.URL,''))) AS socials
from profile p INNER JOIN achievement a ON p.UserId = a.UserId
INNER JOIN social s ON p.UserId = s.UserId
WHERE p.Username LIKE '%uagib%'
group by p.UserId, p.Username, p.TextInfo
答案 1 :(得分:0)
我为此建议子查询:
SELECT p.UserId, p.Username, p.TextInfo,
(SELECT GROUP_CONCAT(COALESCE(a.Rank, ''), '#', COALESCE(a.Tourney, ''))
FROM achievement a
WHERE p.UserId = a.UserId
) as achievements,
(SELECT GROUP_CONCAT(COALESCE(s.platform, ''), '#', COALESCE(s.URL, ''))
FROM social s
WHERE p.UserId = s.UserId
) as socials
FROM profile p
WHERE p.Username LIKE '%uagib%';
注意:
DISTINCT
可能不是必需的,因为沿两个独立的维度进行连接不会产生笛卡尔乘积。CONCAT()
是不必要的。 GROUP_CONCAT()
接受多个参数。