SQL: select all records not selected by another query

前端 未结 3 1144
没有蜡笔的小新
没有蜡笔的小新 2021-01-13 18:30

I am looking for an SQL query to select all records not selected by another query on the same table. Specifically I want to select all records which have duplicates of a pa

相关标签:
3条回答
  • 2021-01-13 19:11

    Specifically I want to select all records which have duplicates of a particular field('fieldA') and then delete all but one of those records.

    In that case, join it:

    delete x 
    from myTable x
     join myTable z on x.field = z.field
    where x.id > z.id
    
    0 讨论(0)
  • 2021-01-13 19:21

    If you change your not IN sub SELECT statement to only return one column (ID), it should work -

    http://blog.sqlauthority.com/2008/04/22/sql-server-better-performance-left-join-or-not-in/

    0 讨论(0)
  • 2021-01-13 19:25

    Something like:

    SELECT id FROM table WHERE id IN (
        SELECT MIN(id) FROM table GROUP BY fieldA HAVING COUNT(*) > 1
    )
    
    0 讨论(0)
提交回复
热议问题