我有一个people
表,其中两个表字段是id
和country
。
我想查找所有具有相同id
和country
的记录,因为id
在每个国家/地区应该是唯一的。
这样做的正确方法是什么?
例如,示例输出应为:
+--------------+---------+
| id | country |
+--------------+---------+
| 123 | AT |
| 123 | AT |
| 456 | GB |
| 456 | GB |
| 456 | GB |
| 789 | AU |
| 789 | AU |
答案 0 :(得分:1)
带有GROUP BY
子句的简单HAVING
就足够了:
SELECT id, country
FROM people
WHERE id <> "" AND id IS NOT NULL
GROUP BY id, country
HAVING COUNT(*) > 1
答案 1 :(得分:0)
SELECT p1.* FROM people p1
INNER JOIN people p2
ON p1.id = p2.id AND p1.country = p2.country
ORDERY BY p1.id
答案 2 :(得分:0)
这可能有效
with cte as (SELECT id -- extracts ID for countryes present more than 1 time
FROM people
GROUP BY id, country
HAVING COUNT(*) > 1)
select id, country -- adds repeated values
from people p join cte on p.id=cte.id