【发布时间】:2013-03-15 21:44:40
【问题描述】:
嗨,我有一张看起来像这样的桌子
-----------------------------------------------------------
| id | group_id | source_id | target_id | sortsequence |
-----------------------------------------------------------
| 2 | 1 | 2 | 4 | 1 |
-----------------------------------------------------------
| 4 | 1 | 20 | 2 | 1 |
-----------------------------------------------------------
| 5 | 1 | 2 | 14 | 1 |
-----------------------------------------------------------
| 7 | 1 | 2 | 7 | 3 |
-----------------------------------------------------------
| 20 | 2 | 20 | 4 | 3 |
-----------------------------------------------------------
| 21 | 2 | 20 | 4 | 1 |
-----------------------------------------------------------
场景
有两种情况需要处理。
-
Sortsequence列值对于source_id和group_id应该是唯一的。例如,如果所有具有group_id = 1 AND source_id = 2的记录都应该具有唯一的排序序列。在上面的示例记录中具有id= and 5 which are having group_id = 1 and source_id = 2 have same sortsequence which is 1。这是错误的记录。我需要找出这些记录。 - 如果
group_id and source_id相同。sortsequence columns value should be continous. There should be no gap。例如上表records having id = 20, 21 having same group_id and source_id and sortsequence value is 3 and 1。即使这是唯一的,但 sortsequence 值也存在差距。我还需要找出这些记录。
我迄今为止的努力
我已经写了一个查询
SELECT source_id,`group_id`,GROUP_CONCAT(id) AS children
FROM
table
GROUP BY source_id,
sortsequence,
`group_id`
HAVING COUNT(*) > 1
这个查询只针对场景1。如何处理场景2?有没有办法在同一个查询中做到这一点,或者我必须编写其他方法来处理第二种情况。
By the way query will be dealing with million of records in table so performance must be very good.
【问题讨论】:
-
排序顺序总是从 1 开始吗?如果是这样,您可以获取 (source_id, group_id) 的排序序列的计数和总和,并应用 n 个数字总和的公式
-
@ChetterHummin 是的,它必须从 1 开始
-
然后我会对这些值求和,看看它是否等于 count*(count+1)/2。不过,这可能需要一个内部查询。 Oracle 可能会提供一些分析功能来为您执行此操作。但我不知道mysql中的等价物
-
@Chetter Hummin 仅按 group_id 和 source_id 分组,然后检查
COUNT(DISTINCT sortsequence) <> COUNT(sortsequence) OR COUNT(sortsequence) <> MAX(sortsequence)应该同时检测到这两个问题的组。