【问题标题】:SQL/Presto: how to choose rows if the values match with another table'sSQL/Presto:如果值与另一个表的匹配,如何选择行
【发布时间】:2021-08-13 11:46:09
【问题描述】:

我有 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 部分出现错误。

【问题讨论】:

  • 此时,与任何有关 MySQL 的基本介绍性书籍或教程在一起 5 分钟都会很有用

标签: mysql sql presto trino


【解决方案1】:

使用左连接和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 

【讨论】:

    【解决方案2】:

    我会推荐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的原因。

    【讨论】:

      猜你喜欢
      • 2021-04-27
      • 1970-01-01
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      相关资源
      最近更新 更多