【问题标题】:Find duplicates in table by checking 4 columns通过检查 4 列查找表中的重复项
【发布时间】:2021-02-10 20:23:25
【问题描述】:

表 * 文章包含 6 7 列。

id  |  Article    | Date        |  Document   |   In    |   Out   |   Status
1       7156       2020-10-26      test           0          14        1
2       7157       2020-10-27      test 2         0          15        1
3       7158       2020-10-28      test 3         0          14        1 
4       7156       2020-10-26      test           0          14        1

有没有一种方法可以找到并列出 4 列(文章、文档、in)的所有重复项。

上表的重复行 id 为 4

4       7156       2020-10-26      test           0          14        1

我正在尝试下面的查询,但没有得到好的结果。

 select s.id, t.* 
    from [articles ] s
    join (
        select Article, Date, Document, Out, count(*) as qty
        from [articles]
        group by Article, Date, Document, Out
        having count(*) > 1
    ) t on s.Article= t.Article and s.Date= t.Date and s.Document= t.Document and s.Out = t.out

在MYSQL中可以直接通过查询找到吗?

【问题讨论】:

    标签: php sql count duplicates subquery


    【解决方案1】:

    你可以这样做:

    select *
    from articles
    where (article, document, in) in (
      select article, document, in 
      from articles 
      group by article, document, in
      habing count(*) > 1
    )
    

    这将返回两个重复的行:

    id  |  Article    | Date        |  Document   |   In    |   Out   |   Status
    1       7156       2020-10-26      test           0          14        1
    4       7156       2020-10-26      test           0          14        1
    

    或者,您可以使用ROW_NUMBER() 来选择基于其id 的行的第二个、第三个等重复项。例如:

    select *
    from (
      select *,
        row_number() over(partition by article, document, in order by id) as rn
      from articles
    ) x
    where rn > 1
    

    【讨论】:

      【解决方案2】:

      我喜欢为此使用exists

      select a.*
      from articles a
      where exists (
          select 1
          from articles a1
          wehre 
              a1.article      = a.article 
              and a1.document = a.document
              and a1.in       = a.in
              and a1.id       < a.id
      )
      

      【讨论】:

        猜你喜欢
        • 2013-02-21
        • 2018-02-12
        • 1970-01-01
        • 2013-11-17
        • 1970-01-01
        • 1970-01-01
        • 2020-04-05
        • 1970-01-01
        相关资源
        最近更新 更多