mysql 4路连接所有字段返回null

标签 mysql

我正在我所在的位置构建一个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/

相关文章:

mysql - 如果 ON 条件在 mysql 中没有匹配数据,如何获取 NULL

Python/MySQL-如何正确使用 %s 来计算行数

mysql - 如何: SQL Query - INNER JOIN with LIMIT 1 on the secondary table?

MySQL选择不在特定日期和时间的id

mysql - 如何检查 pdf 在 mysql 中是否存在或相同的 80%?

mysql - MySQL 中的 IFERROR 函数

php - 如何从 MySQL 数据库表中调用 PHP 函数以便该函数正常运行?

java - 如何减去从 jtextfield 到 mysql 数据库的输入?

mysql - 将别名设置为数据库表字段中的值

php - 如果存在另一个meta_key,则插入meta_key