简体   繁体   中英

Check if column exists in another table

table_1

customer   item  price
Andy       Doll   50
Bella      Robot  25

table_2

customer_name  address 
Andy           Baker Street, London
Carlos         Huntington Street, Newcastle

I would like to create a new column based on whether the value in table_1 exists in table_2. Expected output

customer.   exists_in_table_2
Andy            Yes
Bella           No

My code so far:

select customer, 
case when customer in (select customer_name from table_2) then 'Yes'
else 'No' end as exists_in_table_2

Is there a more efficient way of doing it?

How efficient the query is depends on the database you are using. I usually recommend exists with the appropriate indexes. That would be:

select t1.*, 
       (case when exists (select 1 from table2 t2 where t1.customer = t2.customer_name)
             then 'Yes' else 'No'
        end) as exists_in_table_2
from table1 t1;

The appropriate index is on table2(customer_name) .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM