MySQL 比较两个相似的表,case when not in type 0, else type 1

MySQL diff two similar tables, case when not in type 0, else type 1

假设我有如下两个表,table_atable_b几乎具有相同的数据结构:

table_a
----------------------------
id    name  code     date_a
1    Alice  code_a   2021-01-09 05:23:00
2    Edward code_b   2021-01-14 05:23:00
3    Lann   code_b   2021-01-23 05:23:00
4    Anna   code_c   2021-01-25 05:23:00
....
....
29999 Ben   code_acbd  2021-03-31 05:23:00


table_b
----------------------------
id    name  code     date_b
1    Alice  code_a   2021-01-09 05:23:00
2    Edward code_b   2021-01-14 05:23:00
3    Lann   code_b   2021-01-23 05:23:00
4    Anna   code_c   2021-01-25 05:23:00
....
....
26582 Wesly   code_hsdf  2021-03-14 05:23:00

我可以使用下面的SQL查询3417行table_a不在table_b中,但是不在列表中时如何输入0,否则输入1?

select id from table_a
where date_a between '2021-01-01 00:00:00' and '2021-03-31 23:59:59' and id NOT in 
(select * from(select a.id from table_a a left join table_b b
 on a.id = b.id 
where b.date_b between '2021-01-01 00:00:00' and '2021-03-31 23:59:59' )t1);

我的预期输出是在 table_a 中添加一个新列 is_in_table_bcase when not in 类型 0,否则类型 1

table_a
----------------------------
id    name  code     date_a                is_in_table_b
1    Alice  code_a   2021-01-09 05:23:00     1
2    Edward code_b   2021-01-14 05:23:00     1
3    Kelly   code_b   2021-01-23 05:23:00    0
4    Anna   code_c   2021-01-25 05:23:00     1
....
....
29999 Ben   code_acbd  2021-03-31 05:23:00   0

将逻辑移至 select 子句:

select a.*,
       (exists (select 1
                from table_b b
                where b.id = a.id
               )
       ) as is_in_table_b
from table_a a;

您的查询包含问题未描述的其他过滤条件。您可以在适当的地方将其添加到此查询中。