我正在我所在的位置构建一个sql查询 1)创建一个group_concat,如果值不为空则返回json 2)将一个表(句柄)连接到两个不同的表。
我的查询遇到两个问题
1) 当我得到“应该”失败并返回 0 行的结果时,我得到一行,其中所有字段都为空
2) 当我有一个没有任何事件的场景
时,我最终会得到一个所有字段都为空的JSON_OBJECT
SELECT h.name as name, s.*,
GROUP_CONCAT(JSON_OBJECT(
'activityId', a.id,
'name', ah.name,
'settings', a.settings,
) SEPARATOR ',') as activities
FROM scene AS s
INNER JOIN user AS h ON s.uid = h.id
LEFT JOIN scene_activities AS sa ON sa.sid = s.id
LEFT JOIN activity AS a ON sa.aid = a.id
LEFT JOIN user AS ah ON a.uid = ah.id
WHERE s.scene_id = ?
如何设置上述字段,以便不返回 Scene
的空集或 JSON_OBJECT
的空集为 null。
最佳答案
如果您要求 json 中的所有属性都具有非空值,请不要使用 left
连接(如果没有匹配行,则返回空值)并对也加入行:
SELECT h.name as name, s.*,
GROUP_CONCAT(JSON_OBJECT(
'activityId', a.id,
'name', ah.name,
'settings', a.settings,
) SEPARATOR ',') as activities
FROM scene AS s
JOIN user AS h ON s.uid = h.id
JOIN scene_activities AS sa ON sa.sid = s.id
JOIN activity AS a ON sa.aid = a.id
and a.settings is not null
JOIN user AS ah ON a.uid = ah.id
and ah.name is not null
WHERE s.scene_id = ?
关于mysql 4路连接所有字段返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49332862/