7

嗨,我有一张看起来像的桌子

-----------------------------------------------------------
|  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        |   
-----------------------------------------------------------

设想

有两种情况需要处理。

  1. Sortsequencesource_id列值对于 1和应该是唯一的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. 这是错误的记录。我需要找出这些记录。
  2. 如果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.

4

2 回答 2

1

Tere J从评论中得到答案。以下查询涵盖了上述两个标准。

 SELECT 
     source_id, `group_id`, GROUP_CONCAT(id) AS faultyIDS    
 FROM
     table
 GROUP BY
     source_id,group_id 
 HAVING
     COUNT(DISTINCT sortsequence) <> COUNT(sortsequence) OR COUNT(sortsequence) <> MAX(sortsequence) OR MIN(sortsequence) <> 1

也许它可以帮助别人。

于 2013-03-27T09:57:38.963 回答
0

试试这个查询,它会解决你在问题中提到的这两种情况。

SELECT 
   a.* 
FROM 
   tbl a
INNER JOIN 
   (select 
       @rn:=IF(@prevG = group_id AND @prevS = source_id, @rn + 1, 1) As rId,
       @prevG:=group_id AS group_id, 
       @prevS:=source_id AS source_id, 
       id, 
       sortsequence
    FROM 
       tbl 
    join 
       (select @rn:=0, @prevS:=0, @prevG:=0)b
    order by group_id, source_id, id) b
ON a.id = b.id AND a.SORTSEQUENCE <> b.RID;

小提琴

于 2013-03-26T08:01:53.510 回答