rowid |zipcode | pid ------|---------|--------------------- 1 |14586 | aaaaa 2 |14586 | aaaaa 3 |99001 | bbbbb 4 |99002 | bbbbb 5 |99002 | bbbbb 6 |10006 | ccccc 7 |10007 | ccccc 8 |10008 | ddddd 9 |10009 | eeeee
我想找到pid多次出现的行,而zipcode只出现一次。 例如,我希望查询结果为:
rowid |zipcode | pid ------|---------|--------------------- 3 |99001 | bbbbb 6 |10006 | ccccc 7 |10007 | ccccc
mysql查询语句应该是什么样的?
提前致谢!
答案 0 :(得分:1)
你需要在这里结合一些东西。首先,您需要所有带有计数1的邮政编码,而不是所有带计数的pid>他们需要在同一行。
SELECT * FROM
(SELECT MIN(row_id) as use_row, zipcode, count(zipcode) as zip_count
FROM table
GROUP BY zipcode
HAVING zip_count = 1) as a
JOIN
( SELECT MIN(row_id) as use_row, pid, count(pid) as pid_count
FROM table
GROUP BY pid
HAVING pid_count > 1) as b
ON b.use_row=a.use_row
希望与MIN()的行匹配有效。
答案 1 :(得分:0)
最后找出了一个基于Seb答案的工作查询
SELECT * FROM (SELECT rowid,zipcode,pid FROM table GROUP BY pid,zipcode HAVING count(*) = 1) as a JOIN ( SELECT rowid FROM table where pid IN ( Select * from ( SELECT pid FROM table GROUP BY pid HAVING COUNT(*) >1 ) as b)) as c ON a.rowid = c.rowid