select * duplicatelicates,然后选择* non-duplicates - mysql

时间:2012-10-27 15:29:30

标签: mysql subquery

问题在于示例表结构:

mytable的

fielda, fieldb
val1    valx
val2    valy
val3    valz
val1    vala

我想从mytable中选择一个查询:

fielda, fieldb
val1    valx
val1    vala

基本上从表格中选择*,其中fielda是重复的。

然后使用不同的查询从mytable中选择

fielda, fieldb
val2    valy
val3    valz

fielda上的val1作为副本遇到,因此没有被选中,剩下的就是。

3 个答案:

答案 0 :(得分:3)

此查询对复制fieldA位于列表顶部的表进行排序。

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT fieldA, COUNT(*) totalCount
            FROM tableName
            GROUP BY fieldA
        ) b ON a.fieldA = b.fieldA
ORDER BY b.totalCount DESC

此查询仅选择重复记录。

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT fieldA, COUNT(*) totalCount
            FROM tableName
            GROUP BY fieldA
        ) b ON a.fieldA = b.fieldA
WHERE b.totalCount > 1
ORDER BY b.totalCount DESC

和这个,选择不在第二个查询上的记录(上面

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT fieldA, COUNT(*) totalCount
            FROM tableName
            GROUP BY fieldA
        ) b ON a.fieldA = b.fieldA
WHERE b.totalCount = 1
ORDER BY b.totalCount DESC

答案 1 :(得分:2)

select fielda, fieldb from mytable group by fielda having count(*) >1

select fielda, fieldb from mytable group by fielda having count(*) =1

答案 2 :(得分:0)

第一个:

  

SELECT * FROM tbl GROUP BY fielda HAVING COUNT(*)> 1

第二个:

  

SELECT DISTINCT(fielda)FROM tbl