我有一个表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"
?
答案 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;