MySQL在附加条件下找到最小未使用值

时间:2017-03-07 11:53:39

标签: mysql sql

我有一个表tbl这样的MySQL:

+----+------+
| id | col2 |
+----+------+
| 1  | AAA  |
| 1  | BBB  |
| 2  | AAA  |
| 3  | AAA  |
| 3  | BBB  |
| 4  | AAA  |
+----+------+

如何为col2 col2="BBB"选择第一个未使用的ID(示例返回2)。

基本查询是:

SELECT t1.id+1 AS UnusedID 
FROM tbl AS t1 
LEFT JOIN tbl AS t2 ON t1.id+1 = t2.id 
WHERE t2.id IS NULL 
ORDER BY t1.id LIMIT 1;

但是如何添加条件cl2="BBB"

1 个答案:

答案 0 :(得分:1)

您需要ON子句和WHERE子句中的条件:

SELECT t1.id + 1 AS UnusedID 
FROM tbl t1 LEFT JOIN
     tbl t2
     ON t1.id + 1 = t2.id AND t2.col2 = t1.col2
WHERE t1.col2 = 'BBB' AND t2.id IS NULL 
ORDER BY t1.id
LIMIT 1;