【问题标题】:sql select duplicate rows with multiple OR conditionsql选择具有多个OR条件的重复行
【发布时间】:2021-06-22 00:04:46
【问题描述】:

我检查了https://stackoverflow.com/a/8149330/11343720,但是我想用OR而不是AND更改条件。
我需要使用duplicate name or duplicate city 获取重复数据。
我该怎么做?

select s.id, t.* 
from [stuff] s
join (
    select name, city, count(*) as qty
    from [stuff]
    group by name, city
    having count(*) > 1
) t on s.name = t.name OR s.city = t.city

所以我想做下面这样的 SQL 代码:

select s.id, s.name,s.city 
from stuff s
group by s.name having count(where city OR name are identical) > 1

【问题讨论】:

  • AND 有什么问题?
  • @MERN 为什么这是“你的要求”?谁在给你你的“要求”? (听起来像你有一个微观管理者......)你是否混淆了“或”和“和”的英语定义,而不是“或”和“和”的形式逻辑定义,这实际上非常与英语定义不同?
  • 我们需要您发布您希望看到的“重复数据”的具体示例 - 因为过度包含的连接条件将始终导致在输出中的重复行中,但这并不意味着存在重复的 源数据
  • @Strawberry,好的,我想结束这个问题,请帮帮我

标签: mysql sql select


【解决方案1】:

也许我最初误解了你。您想要名称或城市重复,对吗?

select s.* 
from [stuff] s
where name in 
(
    select name
    from [stuff]
    group by name
    having count(*) > 1
) OR
city in (select city
    from [stuff]
    group by city
    having count(*) > 1) 

【讨论】:

    【解决方案2】:

    我需要获取具有重复名称或重复城市的重复数据。

    我会建议窗口函数:

    select s.*
    from (select s.*,
                 count(*) over (partition by name) as name_cnt,
                 count(*) over (partition by city) as city_cnt
          from stuff s
         ) s
    where name_cnt > 1 or city_cnt > 1;
    

    【讨论】:

      【解决方案3】:

      我试图使此解决方案与您链接的原始解决方案相似。

      select s.id, 
             t.* 
      from [stuff] s
      join (
          select t.name, 
                 t.city
          from [stuff] t
          join [stuff] t2
          on t.name = t2.name
              or t.city = t2.city
          group by t.name, t.city
          having count(*) > 1
      ) t 
      on coalesce(s.name,'') = coalesce(t.name,'')
      and coalesce(s.city,'') = coalesce(t.city,'')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-18
        • 1970-01-01
        • 2017-06-05
        • 1970-01-01
        • 1970-01-01
        • 2020-01-31
        • 2020-10-26
        相关资源
        最近更新 更多