SQL/Presto:如果值与另一个 table 匹配,如何选择行

SQL/Presto: how to choose rows if the values match with another table's

我有 2 个 table:

table 1:

task  cnt 
1      4
2      5
3      6

table 2:

task   cnt2
 1     7
 2     5
 3     6
 4     3

我想为 table 2 添加一列,如果 table1 中任务的 cnt 与 table2 中任务的 cnt2 相同。如果没有匹配,则将其标记为 'no match'

想要的结果:

 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 都支持布尔表达式,所以你可以使用:

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 表达式将其转换为字符串,但我更喜欢布尔标志。

注意:如果 table1 中有多个匹配项,则左联接可以增加行数。这就是我推荐 exists.

的原因