在 sub_category_id 为 NULL 的情况下,我也尝试选择 report_id 和 report_name
示例数据:
table research_category
category_id | category name
---------------------------
1 | category_one
2 | category_two
3 | category_three
table research_sub_category
sub_category_id | category_id | sub_category name
-------------------------------------------------
1 | 1 | sub_category_one
2 | 3 | sub_category_two
table research_report_detail
category_id | sub_category_id | report_id | report_name
-----------------------------------------------------------------------------
1 | 1 | 1 | Awesome Report
2 | NULL | 2 | Awesome? We'll Never Know, Report
3 | 2 | 3 | Another Boring Report, yo
下面的查询返回我想要的结构,但我似乎无法返回report_id | sub_category_id 为 NULL 的情况的报告名称。
SELECT c.category_id, c.category_name, s.sub_category_id, s.sub_category_name, r.report_id, r.report_name
FROM research_category AS c
LEFT JOIN research_sub_category AS s
ON c.category_id = s.category_id
LEFT JOIN research_report_detail AS r
ON s.sub_category_id = r.sub_category_id
LEFT JOIN research_report_detail AS r2
ON c.category_id = r2.category_id
AND r2.sub_category_id IS NULL
返回数据:
category_id|category_name |sub_category_id|sub_category_name|report_id|report_name
-------------------------------------------------------------------------------------
1 |category_one |1 |sub_category_one |1 |Awesome report
2 |category_two |NULL |NULL |NULL |NULL
3 |category_three|2 |sub_category_two |3 |Boring Report
我究竟做错了什么?
编辑:更改了以下内容
AND r2.sub_category_id = NULL
至
AND r2.sub_category_id IS NULL
但是得到了同样的结果......
**双重编辑:向数据添加了另一个报告以使问题更加清晰