如果记录存在于相关 table 中,则带有 1 和 0 的 sqlite 额外列

sqlite extra column with 1 and 0 if record exists in related table or not

我不太擅长SQL,所以我有以下table

东西

专业

比方说,名字为'Bob'的工人有两个专长。如果记录存在于 Stuff 中,我如何获得带有额外列(假设计数)的专业 table,如果记录存在于 Stuff 中,则该列为 1,否则为 0。

请问有没有什么办法可以投查询 returns Bob 的结果如下所示?

任何建议都会很有帮助。先感谢您。 (标题不太清楚,有更好的建议请指教!)

使用 Left Outer joinNull 检查。试试这个。

SELECT sp.specialitycode,
       sp.description,
       CASE
         WHEN st.specialitycode IS NULL THEN 0
         ELSE 1
       END AS count
FROM   speciality sp
       LEFT OUTER JOIN (SELECT specialitycode
                        FROM   stuff
                        WHERE  surname = 'Bob') st
                    ON sp.specialitycode = st.specialitycode 

我倾向于使用 caseexists:

select sp.*,
       (case when exists (select 1
                          from stuff s
                          where s.surname = 'Bob' and
                                s.speciality_code = sp.speciality_code
                         )
             then 1 else 0
        end) as BobHas
from specialty sp;