0

在 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

但是得到了同样的结果......

**双重编辑:向数据添加了另一个报告以使问题更加清晰

4

3 回答 3

1

尝试使用“is null”我认为问题在于您正在尝试使用等号(=)。Null 不存在,因此您无法检查它是否等于某个值。

查看此链接http://www.w3schools.com/sql/sql_null_values.asp

于 2012-11-27T18:41:08.333 回答
1

改变

SELECT c.category_id, ... r.report_id, r.report_name

SELECT c.category_id, ... r2.report_id, r2.report_name
于 2012-11-27T18:42:26.873 回答
1

此查询应与更新后的问题匹配:您不应使用两个 research_report_detail 实例,而应仅使用一个实例,当且仅当给定 sub_category_id(非空)时,将其连接到 research_sub_category 的连接条件。

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 s.category_id = c.category_id
LEFT JOIN research_report_detail AS r
ON r.category_id = c.category_id
AND (r.sub_category_id = s.sub_category_id OR r.sub_category_id IS NULL)
于 2012-11-27T19:06:35.650 回答