我有一个像这样的2D数组:
row | user_id | risk_id | measure_id | description --------------------------------------------------- 0 | 73 | 12 | 32 | 'foo' 1 | 73 | 12 | 32 | 'bar' 2 | 31 | 23 | 31 | 'foobar' 3 | 31 | 23 | 31 | 'foo'
我想检查user_id,risk_id和measure_id之间的组合是否唯一,如果没有返回另一个2D数组,其中行为user_id,列为行,如下所示
user_id | row_0 | row_1 | ...... -------------------------------- 73 | 0 | 1 | ...... 31 | 2 | 3 | ......
答案 0 :(得分:0)
这是为了查找重复项,但会返回行,而不是列:
SELECT x.user_id, x.row
FROM YOUR_TABLE x
JOIN (SELECT t.user_id
FROM YOUR_TABLE t
GROUP BY t.user_id, risk_id, measure_id
HAVING COUNT(t.user_id) > 1) y ON y.user_id= x.user_id;
这个将返回按user_id
分组的表格,以及在rows
列中分隔的以逗号分隔的重复行:
user_id | rows
72 | 0, 1
31 | 2, 3
SELECT x.user_id, GROUP_CONCAT(x.row SEPARATOR ',') as rows
FROM YOUR_TABLE x
JOIN (SELECT t.user_id
FROM YOUR_TABLE t
GROUP BY t.user_id, risk_id, measure_id
HAVING COUNT(t.user_id) > 1) y ON y.user_id= x.user_id
GROUP BY x.user_id;