MySQL检查一对多关系中的重复条目

时间:2016-05-16 14:27:23

标签: mysql duplicates one-to-many

我有两对一对多的关系表。我想检查映射表中是否有任何重复的条目。

客户:

+----------------------------+--------------+------+-----+---------+----------------+
| Field                      | Type         | Null | Key | Default | Extra          |
+----------------------------+--------------+------+-----+---------+----------------+
| uid                        | int(11)      | NO   | PRI |         | auto_increment |
| active                     | tinyint(1)   | NO   |     |         |                |
| locked                     | tinyint(1)   | NO   |     |         |                |
+----------------------------+--------------+------+-----+---------+----------------+

items_mapping:

+--------------+---------------+------+-----+---------+----------------+
| Field        | Type          | Null | Key | Default | Extra          |
+--------------+---------------+------+-----+---------+----------------+
| uid          | int(11)       | NO   | PRI |         | auto_increment |
| customer_uid | int(11)       | NO   |     |         |                |
| device_uid   | int(11)       | NO   |     |         |                |
| offered      | float(11,2)   | NO   |     |         |                |
+--------------+---------------+------+-----+---------+----------------+

如何检查表table_mapping中是否有任何客户,谁有重复的device_uid?

简而言之,这将有效:

+-------+--------------+------------+---------+
| uid   | customer_uid | device_uid | offered |
+-------+--------------+------------+---------+
|  1132 |   53442      |      24    |  2.00   |
|  8242 |   53442      |      45    |  4.00   |
| 15122 |   53442      |      12    |  5.00   |
+-------+--------------+------------+---------+

但它不应该是:

+-------+--------------+------------+---------+
| uid   | customer_uid | device_uid | offered |
+-------+--------------+------------+---------+
|  1132 |   53442      |      24    |  2.00   |
|  8242 |   53442      |      45    |  4.00   |
| 15122 |   53442      |      24    |  2.00   |
+-------+--------------+------------+---------+

2 个答案:

答案 0 :(得分:1)

只需按customer_uiddevice_uid以及having条款分组:

SELECT
    customer_uid,
    device_uid,
    COUNT(device_uid) count_device_uid
FROM
    items_mapping
GROUP BY
    customer_uid,
    device_uid
HAVING
    COUNT(device_uid) > 1

这将为所有客户提供重复的device_uid

答案 1 :(得分:1)

不确定它是否会运行,但这会产生结果:

SELECT 
    COUNT(*),
    customer_id,
    device_uid,
FROM 
    items_mapping
GROUP BY
    device_uid, customer_id
HAVING COUNT(*) > 1