I currently have 2 SQL tables: table1
and table2
. table1
has 2 columns called id_a
and column_a
. table2
has 2 columns called id_b
and column_b
.
I would like to create a new_column
in table1
. The value of new_column
should be 1 if the value of table1.id_a
exists in table2.id_b
. Otherwise, new_column
should have the value of 0.
How do I do this? I'm using SQLite3 and table1
is significantly larger than table2
.
How about a simple exists
?
select t1.*,
(case when exists (select 1 from table2 t2 where t2.id_b = t1.id_a)
then 1 else 0
end) as flag
from table1 t1
A left join
solution for fun! In certain circumstances might even be more efficient than correlated subquery as well.
select
t1.*,
case
when t2.id_b is null then 0
else 1
end as new_column
from
table1 t1
left join
table2 t2
on t2.id_b = t1.id_a
How about a simple IN
?
SELECT *,
id_a IN (SELECT id_b FROM table2) AS flag
FROM table1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.