[英]SQL/Presto: how to choose rows if the values match with another table's
我有 2 張桌子:
表格1:
task cnt
1 4
2 5
3 6
表2:
task cnt2
1 7
2 5
3 6
4 3
我想為表 2 添加一列,這樣如果表 1 中任務的 cnt 與表 2 中任務的 cnt2 相同。 如果沒有匹配,則將其標記為“不匹配”
期望的結果:
task cnt2 if_matched
1 7 'no match'
2 5 'yes'
3 6 'yes'
4 3 'no match'
我從像下面這樣的查詢開始選擇具有匹配值的任務
select task from table1 where table1.cnt = table2.cnt2
但我在 where 部分遇到了錯誤。
使用左連接和 case 表達式計算匹配:
select t2.task, t2.cnt,
case when t1.task is null then 'no match' else 'yes' end as matched
from table2 t2
left join table1 t1 on t1.task=t2.task and t1.cnt = t2.cnt2
我會推薦exists
。 Presto 和 MySQL 都支持 boolean 表達式,因此您可以使用:
select t2.*,
(exists (select 1 from table1 t1 where t1.task = t2.task and t1.cnt = t2.cnt)
) as t1_matches
from table2 t2;
您可以使用case
表達式將其轉換為字符串,但我更喜歡 boolean 標志。
注意:如果table1
中有多個匹配項,則左連接可以增加行數。 這就是我推薦exists
的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.