将表视为 -
mysql> SELECT * FROM DB;
+------+--------+------+------------+---------+
| UDID | BENEID | DEPT | SCHEME | NAME |
+------+--------+------+------------+---------+
| 1 | 55 | TCS | RC | SHELLY |
| 2 | 95 | TCS | RC | BOB |
| 3 | 75 | TCS | RC | ULRICH |
| 4 | 55 | TCS | RC | SHELLY |
| 5 | 85 | TCS | FS | SHELLY |
| 6 | 65 | DSSP | ABC | BOB |
| 7 | 65 | DSSP | ABC | BOB |
| 8 | 75 | DSSP | ABC | ULRICH |
+------+--------+------+------------+---------+
列 beneid,dept 和 scheme 的列重复,具有不同的主键,udid 。就是这样,
mysql> SELECT DEPT, SCHEME, BENEID, COUNT(*) AS CN FROM DB GROUP BY 1, 2, 3 HAVING CN >1;
+------+--------+--------+----+
| DEPT | SCHEME | BENEID | CN |
+------+--------+--------+----+
| DSSP | ABC | 65 | 2 |
| TCS | RC | 55 | 2 |
+------+--------+--------+----+
我们有2个重复列,用于dept,scheme,beneid但具有不同的主键(udid)。 如何列出上述结果的udids?
预期的表格结构 -
+------+--------+--------+----+-----+
| DEPT | SCHEME | BENEID | CN | UDID|
+------+--------+--------+----+-----+
| DSSP | ABC | 65 | 2 | 6 |
| DSSP | ABC | 65 | 2 | 7 |
| TCS | RC | 55 | 2 | 1 |
| TCS | RC | 55 | 2 | 4 |
+------+--------+--------+----+-----+
答案 0 :(得分:1)
您需要“返回”原始表格,方法是将此表格过滤为您发现为重复的行。
示例:
SELECT DB.DEPT, DB.SCHEME, DB.BENEID, DUPS.CN, DB.UID
FROM DB
INNER JOIN
(
SELECT DEPT, SCHEME, BENEID, COUNT(*) AS CN
FROM DB GROUP BY 1, 2, 3 HAVING CN >1
) AS DUPS ON DB.DEPT = DUPS.DEPT
and DB.SCHEME = DUPS.SCHEME
and DB.BENEID = DUPS.BENEID
答案 1 :(得分:1)
您可以使用列为子查询的聚合查询,并使用exists
调用将其打包:
SELECT *
FROM db a
WHERE EXISTS (SELECT b.dept, b.scheme, b.beneid
FROM db b
WHERE a.dept = b.dept AND
a.scheme = b.scheme AND
a.beneid = b.beneid
GROUP BY b.dept, b.scheme, b.beneid
HAVING COUNT(*) > 1)