MySQL选择检测组内互斥的行冲突

时间:2015-08-05 18:19:23

标签: mysql select

使用以下示例数据,我想创建一个查询,该查询可以找到item / desc重复的位置,并且它们各自的数据字段不是互斥的。含义...对于给定的item / desc组合,列中只能有1个数据值。

样本表记录:

id  | item  |  desc | data1 | data2 | data3
----+-------+-------+-------+-------+-------
1   |   1   | cat   |   a   |       |
2   |   1   | cat   |       |   b   |
3   |   1   | cat   |       |   e   |
4   |   2   | dog   |   a   |       |          
5   |   2   | dog   |       |   h   |   f
6   |   3   | apple |   k   |       |   m
7   |   3   | worm  |   a   |   g   |   x
8   |   4   | rock  |   p   |       |   s
9   |   4   | rock  |       |       |   s
10  |   4   | rock  |       |   t   |   z

预期查询结果:

 item  |  desc 
-------+-------
   1   | cat                (because of conflict in data2 with b & e)
   4   | rock               (because of conflict in data3 with s,s & z

2 个答案:

答案 0 :(得分:3)

这应该有效:

select distinct 
item,
`desc`
from
table
group by item, `desc`
HAVING count(distinct data1) > 1 or count(distinct data2) > 1 or count(distinct data3) > 1

答案 1 :(得分:1)

您可以执行简单的计数聚合和HAVING子句来实现此目的。

SELECT `item`,
   `desc`,
   COUNT(`data1`) AS `data1count`,
   COUNT(`data2`) AS `data2count`,
   COUNT(`data3`) AS `data3count`
FROM table
GROUP BY `item`, `desc`
HAVING `data1count` > 1
   OR `data2count` > 1
   OR `data3count` > 1