我有以下sql处理1个需要帮助的小问题。即使连接的表之一为空,我也需要显示结果。我曾尝试使用左/右联接,但似乎没有什么不同,我需要使用什么来完成这项工作?
现在,查询将一直有效,除非表dx_code_ Patient中的记录不匹配,即使该表中没有匹配的记录,我也需要显示结果。
SELECT
group_concat(distinct current_dx.dx_code_with, ': ', current_dx.description SEPARATOR ' - ') AS current_dxc,
group_concat(distinct pending_dx.dx_code_with, ': ', pending_dx.description SEPARATOR ' - ') AS pending_dxc,
p.id, p.first_name, p.last_name
FROM patients AS p
INNER JOIN tmp_dx_code_patient AS tmp_dx
ON tmp_dx.patient_id = p.id
INNER JOIN dx_code_patient AS cdx
ON cdx.patient_id = p.id
INNER JOIN dx_codes AS current_dx
ON current_dx.id = cdx.dx_code_id
INNER JOIN dx_codes AS pending_dx
ON pending_dx.id = tmp_dx.dx_code_id
GROUP BY p.id
ORDER BY tmp_dx.created_at asc
当前结果:
+----------------+--------------+----+------------+-----------+
| current_dxc | pending_dxc | id | first_name | last_name |
+----------------+--------------+----+------------+-----------+
| def: something | 123: message | 2 | Bob | Smith |
+----------------+--------------+----+------------+-----------+
预期
+----------------+---------------+----+------------+------------+
| current_dxc | pending_dxc | id | first_name | last_name |
+----------------+---------------+----+------------+------------+
| null | ghy: hi | 1 | Mike | Jones |
+----------------+---------------+----+------------+------------+
| def: something | 123: message | 2 | Bob | Smith |
+----------------+---------------+----+------------+------------+
| null | 432: question | 3 | John | Doe |
+----------------+---------------+----+------------+------------+
答案 0 :(得分:1)
JOIN
不返回NULL
结果。我的猜测是您的意思是没有行匹配。如果是这样,LEFT JOIN
应该可以解决您的问题。在整个FROM
子句中使用它:
FROM patients p LEFT JOIN
tmp_dx_code_patient tmp_dx
ON tmp_dx.patient_id = p.id LEFT JOIN
dx_code_patient cdx
ON cdx.patient_id = p.id LEFT JOIN
dx_codes current_dx
ON current_dx.id = cdx.dx_code_id LEFT JOIN
dx_codes pending_dx
ON pending_dx.id = tmp_dx.dx_code_id