检查MySQL中不同行的相同值

时间:2018-03-11 13:06:00

标签: mysql

我刚开始学习MySQL,我对一个特定的查询有疑问。我有一张名为&table;' table1'如下:

enter image description here

我想知道是否有不同的行具有相同的性别,年龄和邮政编码值。在这种情况下,查询应显示:

enter image description here

目前,为了解决这个问题,我只使用GROUP BY并手动检查它们:

 SELECT * FROM table1
 GROUP BY Gender, age, postcode

但是对于更大的数据,手动检查它们太难了。

任何人都可以帮助我吗?

由于

3 个答案:

答案 0 :(得分:0)

您可以使用如下查询:

    SELECT t1.Gender, t1.Age, t1.Postcode FROM table1 t1
    GROUP BY CONCAT_WS(Gender, Age, postcode)
    HAVING sum(1) >1
) f
LEFT JOIN table1 t2
     ON t2.Gender = f.Gender AND t2.Age = f.Age AND t2.postcode = f.postcode

ORDER BY t2.postcode, t2.Age, t2.Gender;

<强>示例

MariaDB [bernd]> select * from table1;
+------+--------+------+----------+-----------+
| Name | Gender | age  | postcode | member_id |
+------+--------+------+----------+-----------+
| A    | M      |   18 | 2112     |     10001 |
| B    | M      |   19 | 2012     |     10002 |
| C    | F      |   23 | 1345     |     10003 |
| D    | M      |   23 | 3145     |     10004 |
| F    | M      |   23 | 4567     |     10005 |
| G    | F      |   21 | 1022     |     10006 |
| H    | M      |   18 | 2112     |     10007 |
| I    | F      |   21 | 8694     |     10008 |
| J    | F      |   25 | 7865     |     10009 |
| K    | F      |   24 | 7869     |     10010 |
| L    | F      |   21 | 1022     |     10011 |
+------+--------+------+----------+-----------+
11 rows in set (0.00 sec)

MariaDB [bernd]> SELECT t2.* FROM (
    ->     SELECT t1.Gender, t1.Age, t1.Postcode FROM table1 t1
    ->     GROUP BY CONCAT_WS(Gender, Age, postcode)
    ->     HAVING sum(1) >1
    -> ) f
    -> LEFT JOIN table1 t2
    ->      ON t2.Gender = f.Gender AND t2.Age = f.Age AND t2.postcode = f.postcode
    ->
    -> ORDER BY t2.postcode, t2.Age, t2.Gender;
+------+--------+------+----------+-----------+
| Name | Gender | age  | postcode | member_id |
+------+--------+------+----------+-----------+
| L    | F      |   21 | 1022     |     10011 |
| G    | F      |   21 | 1022     |     10006 |
| H    | M      |   18 | 2112     |     10007 |
| A    | M      |   18 | 2112     |     10001 |
+------+--------+------+----------+-----------+
4 rows in set (0.01 sec)

MariaDB [bernd]>

答案 1 :(得分:0)

使用自我加入

select * from t t1, t t2 where (t1.x = t2.x) and (t1.id != t2. id)

请注意,x是您需要在其值中找到重复的列,而id是主键

答案 2 :(得分:-1)

要获取具有重复项的数据行,请执行以下操作:

SELECT Gender, age, postcode, GROUP_CONCAT(DISTINCT Name), GROUP_CONCAT(DISTINCT member_id)
FROM table1
GROUP BY Gender, age, postcode
HAVING COUNT(*)>1;