在不同的字段中查找具有相等值的记录?

时间:2019-01-23 14:46:09

标签: mysql sql

我有一个people表,其中两个表字段是idcountry

我想查找所有具有相同idcountry的记录,因为id在每个国家/地区应该是唯一的。

这样做的正确方法是什么?

例如,示例输出应为:

+--------------+---------+
| id           | country |
+--------------+---------+
| 123          | AT      |
| 123          | AT      |
| 456          | GB      |
| 456          | GB      |
| 456          | GB      |
| 789          | AU      |
| 789          | AU      |

3 个答案:

答案 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