【问题标题】:SQL which OR condition matched scoringOR 条件匹配评分的 SQL
【发布时间】:2017-09-04 23:43:50
【问题描述】:

我有一个要求,我要自己加入一个表,例如员工,我的条件是名字匹配加上任何三列要么姓氏匹配要么出生日期或电子邮件或电话或城市或国家匹配所以名字必须匹配,然后提到的三列中的任何一个都匹配,我该怎么做我的 sql?

SQL 类似于:

where c1.firstname=c2.firstname
and ( c1.lastname = c2.lastname or c1.dob = c2.dob or ....)

我很难执行任何 3 个属性匹配的要求

【问题讨论】:

  • 你的方法没问题。用括号括住个别条件。
  • 您使用的是 SQL Server 还是 Oracle?只标记您真正使用的产品。

标签: sql sql-server


【解决方案1】:

您可以将OR 替换为为每个匹配添加1 的条件总和,计算匹配数并过滤总数:

where c1.firstname=c2.firstname and
    (case when c1.lastname = c2.lastname then 1 else 0 end
    +case when c1.dob = c2.dob then 1 else 0 end
    +case when c1.addr1 = c2.addr1 then 1 else 0 end
    +case when c1.addr2 = c2.addr2 then 1 else 0 end
    +case when c1.phone = c2.phone then 1 else 0 end) >= 3

【讨论】:

    【解决方案2】:

    首先,您应该在 on 子句中进行比较,而不是在 where 子句中进行比较。

    其次,你可以统计比赛:

    select c1.*, c2.*
    from c c1 join
         c c2
         on c1.firstname = c2.firstname and
            ((case when c1.lastname = c2.lastname then 1 else 0 end) + 
             (case when c1.dob = c2.dob then 1 else 0 end) + 
             (case when c1.email = c2.email then 1 else 0 end) + 
             (case when c1.phone = c2.phone then 1 else 0 end) + 
             (case when c1.city = c2.city then 1 else 0 end) + 
             (case when c1.country = c2.country then 1 else 0 end)
            ) >= 3;
    

    第三,注意比赛。如果city 匹配,那么country 可能也匹配——很多人可以在同一个城市有相同的名字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 2017-10-31
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多