MySQL - 获取缺少2列的ID

时间:2015-06-23 16:00:21

标签: mysql select

我有一张这样的表:

  
Code | ID |
 AAA | 1  |
 AAA | 2  |
 AAA | 4  |
 AAA | 5  |
 BBB | 1  |
 BBB | 4  |
 BBB | 5  |
 BBB | 6  |

仅使用选择查询可以列出缺少的“代码”和“id”吗?

  
Code | ID |
 AAA | 3  |
 BBB | 2  |
 BBB | 3  |

我在下面的链接中找到了一个中途解决方案代码(仅适用于一列): MySQL get missing IDs from table 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

它非常相似,您只需要在where子句和group by子句中包含另一列:

SELECT a.id+1 AS start, MIN(b.id) - 1 AS end
    FROM testtable AS a, testtable AS b
    WHERE a.id < b.id AND a.code = b.code
    GROUP BY a.code, a.id
    HAVING start < MIN(b.id)