检查关系是否存在并返回true或false

时间:2016-06-28 03:49:06

标签: sql join relational-database

我有3个表,Category StepCategoryStep,其中CategoryStep将其他两个表关联在一起。我希望使用真/假列返回所有类别,无论CategoryStep中是否存在基于StepID的关系。

表的架构很简单,

Category:
CategoryID      | CategoryName

Step:
StepID          | StepName

CategoryStep:
CategoryStepID  | CategoryID    | StepID

当尝试根据StepID获得结果时,我只获得存在的关系,而不是那些不存在的关系。

SELECT [CategoryID], [Category], CAST(CASE WHEN [CategoryStep].[CategoryStep] IS NULL THEN 0 ELSE 1 END AS BIT) AS related
FROM Category
LEFT JOIN CategoryStep ON Category.CategoryID = CategoryStep.CategoryID
INNER JOIN Step ON CategoryStep.StepID = Step.StepID
WHERE Step.StepID = 2

步骤表:

|StepID | StepName
|-------|---------
| 1     | StepOne
| 2     | StepTwo
| 3     | StepThree

类别表:

| CategoryID | CategoryName
|------------|-------------
| 1          | Holidays
| 2          | States
| 3          | Cities
| 4          | Animals
| 5          | Food

CategoryStep表

| CategoryStepID | CategoryID | StepID
|----------------|------------|-------
| 1              | 1          | 1
| 2              | 1          | 2     <--
| 3              | 2          | 1
| 4              | 2          | 3
| 5              | 3          | 2     <--
| 6              | 4          | 1
| 7              | 4          | 2     <--
| 8              | 4          | 3
| 9              | 5          | 1
| 10             | 5          | 3

所以,如果我正在寻找StepID = 2,我正在寻找的结果表是:

| CategoryID | Category | Related
|------------|----------|--------
| 1          | Holidays | 1
| 2          | States   | 0
| 3          | Cities   | 1
| 4          | Animals  | 1
| 5          | Food     | 0

1 个答案:

答案 0 :(得分:4)

尝试将INNER JOIN替换为LEFT JOIN

<强>更新

原始尝试的致命缺陷是WHERE条款。您正在执行正确的LEFT JOIN,但WHERE子句正在过滤掉不匹配的类别记录。在下面的查询中,我将步骤ID的检查移动到它所属的连接条件。

SELECT [CategoryID], [Category],
    CAST(CASE WHEN [CategoryStep].[CategoryStep] IS NULL THEN 0 ELSE 1 END AS BIT) AS related
FROM Category
LEFT JOIN CategoryStep
    ON Category.CategoryID = CategoryStep.CategoryID AND
       CategoryStep.StepCodeID = 2
LEFT JOIN Step
    ON CategoryStep.StepID = Step.StepID