sql - 检查列是否存在于另一个表中
问题描述
表格1
customer item price
Andy Doll 50
Bella Robot 25
表_2
customer_name address
Andy Baker Street, London
Carlos Huntington Street, Newcastle
我想根据 table_1 中的值是否存在于 table_2 中创建一个新列。预期产出
customer. exists_in_table_2
Andy Yes
Bella No
到目前为止我的代码:
select customer,
case when customer in (select customer_name from table_2) then 'Yes'
else 'No' end as exists_in_table_2
有没有更有效的方法呢?
解决方案
查询的效率取决于您使用的数据库。我通常建议exists
使用适当的索引。那将是:
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;
适当的索引是 on table2(customer_name)
。
推荐阅读
- javascript - 从键入的签名中恢复公共地址
- reactjs - Jest.js 强制窗口未定义
- php - MySQL PHP - UTF8 数据插入编码
- selenium - TFS 构建运行功能测试任务:“DistributedTests:测试运行 '[run#]' 处于 'InProgress' 状态。”
- npm - 在窗口 10 中反应本机守望者错误
- corda - 在 Corda 中,附件大小有上限吗?
- c# - 为什么相同的代码在调试和发布版本之间呈现不同的结果
- ffmpeg - 为输出文件 #0 (360p.m3u 8) 指定的编解码器 AVOption b(设置比特率(以比特/秒为单位))尚未用于任何流。
- sql - 计算 X 英里内的点数 SQL
- git - 如何让 GitHub Pages 重新渲染我的 React 应用程序?