SQL Find rows that violate UNIQUE together index

廉价感情. 提交于 2019-12-12 07:26:23

问题


i want to put unique index on two (or more) columns in a table, but i get "duplicate keys found". How to select those rows which cause duplication?


回答1:


You can use Group By and Having for this:

SELECT col1,
       col2
FROM   table
GROUP  BY col1,
          col2
HAVING Count(*) > 1

Basically - group the values, then filter for instances where there is more than one.




回答2:


You could use one of the following ways:

SELECT t1.rowid
FROM   this_table t1
WHERE  EXISTS (SELECT '1'
               FROM   this_table t2
               WHERE  t2.column_value1 = t1.column_value1
                      AND t2.column_value2 = t1.column_value2
                      AND t2.rowid > t1.rowid);

SELECT *
FROM   this_table_name a
WHERE  a.rowid > ANY (SELECT b.rowid
                      FROM   this_table_name b
                      WHERE  a.col1 = b.col1
                             AND a.col2 = b.col2);

SELECT my_column,
       Count(my_column)
FROM   this_table_name
GROUP  BY my_column
HAVING Count (my_column) > 1;


来源:https://stackoverflow.com/questions/12033877/sql-find-rows-that-violate-unique-together-index

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!