gpt4 book ai didi

sql - 检查关系是否存在并返回真或假

转载 作者:行者123 更新时间:2023-12-03 22:42:53 25 4
gpt4 key购买 nike

我有 3 张 table ,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

类别步骤表
| 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

最佳答案

尝试更换 INNER JOINLEFT 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

关于sql - 检查关系是否存在并返回真或假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38066741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com