SQL table 中没有记录时获取结果的代码

SQL Code to get results when there are no records in a table

有 4 个 table(用户、用户选项、选项类型 1 和选项类型 2)。此处并未直接涉及用户 table,但为了完整性而提及。以下是涉及的每个 table 的 table 列。

User Options:
    UserID,
    Option1ID,
    Option2ID,

Option1:
    Option1ID,
    Option1Description

Option2:
    Option2ID,
    Option2Description

选项 1 的所有值都可以与选项 2 的所有值组合,因此如果有 'x' 个选项 1 值和 'y' 个选项 2 值,则选项组合的结果数为'x' * 'y'。我想编写一个查询,即使在 UserOptions table。此外,应该有一列指示 Option1 和 Option2 的特定组合是否存在于 UserOptions table.

Option1
Option1ID   Option1Description
----------------------------------
1           1_Description1
2           1_Description2


Options2
Option2ID   Option2Description
----------------------------------
1           2_Description1
2           2_Description2


UserOptions
UserID  Option1ID   Option2ID
---------------------------------
1       1           2
1       2           2


Result
UserID  Option1ID   Option2ID   Exists
----------------------------------------------
1       1           1           0
1       1           2           1
1       2           1           0
1       2           2           1

鉴于上述情况,SQL 查询是什么?另外请注意,UserID = 2 不存在于 UsersOptions table 中。在这种情况下,查询仍应 return 4 条记录,其中 UserID 列始终为 2,OptionID 列相同,Exists 列始终为 0。

您可以 cross join 用户 table 使用两个选项 tables 生成所有可能的组合,然后在桥 table [=13] 中搜索匹配项=] 与 left join:

select u.userid, o1.option1id, o2.option2id, 
    case when uo.userid is null then 0 else 1 end as uo_exists
from users u
cross join option1 o1
cross join option2 o2
left join useroptions uo 
    on  uo.userid = u.id
    and uo.option1id = o1.option1id
    and uo.option2id = o1.option2id

您也可以使用 exists 而不是 left join:

select u.userid, o1.option1id, o2.option2id, 
    case when exists (
        select 1 
        from useroptions uo 
        where  uo.userid = u.id and uo.option1id = o1.option1id and uo.option2id = o1.option2iduo.userid
    ) then 1 else 0 end as uo_exists
from users u
cross join option1 o1
cross join option2 o2