我有一个像 (1,2,3,4,5,6) 这样的 ID 列表。我想找出列表中的这些 id 中有多少不存在于表中。我该怎么做呢 ?
-- table --
id name
1 a
2 b
3 c
4 d
5 e
6 f
7 g
我得到的 ID 列表是 1,2,3,4,5,6,7,8,9,10,11,12,13
所以当查询我应该得到像 8,9,10,11,12,13 这样不在表中的结果
我有一个像 (1,2,3,4,5,6) 这样的 ID 列表。我想找出列表中的这些 id 中有多少不存在于表中。我该怎么做呢 ?
-- table --
id name
1 a
2 b
3 c
4 d
5 e
6 f
7 g
我得到的 ID 列表是 1,2,3,4,5,6,7,8,9,10,11,12,13
所以当查询我应该得到像 8,9,10,11,12,13 这样不在表中的结果
尝试这个:
SELECT
6-c
FROM (
SELECT
COUNT(DISTINCT(ID)) as c
FROM
my_table
WHERE
ID IN (1,2,3,4,5,6)
) as tmp
并找出缺少哪些:
SELECT
zID
FROM (
SELECT 1 as zID UNION
SELECT 2 as zID UNION
SELECT 3 as zID UNION
SELECT 4 as zID UNION
SELECT 5 as zID UNION
SELECT 6 as zID UNION
SELECT 7 as zID UNION
SELECT 8 as zID UNION
SELECT 9 as zID UNION
SELECT 10 as zID UNION
SELECT 11 as zID UNION
SELECT 12 as zID UNION
SELECT 13 as zID UNION
SELECT 14 as zID UNION
SELECT 15 as zID UNION
) as t1
LEFT JOIN (
SELECT
DISTINCT(ID) as mID
FROM
my_table
) as t2
ON t1.zID = t2.mID
WHERE
t2.mID IS NULL
这将返回列表中不在表中的 ID 列表。
SELECT t1.id
FROM (SELECT 1 id
UNION
SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6) t1
LEFT JOIN MyTable t2
ON t1.id = t2.id
WHERE t2.id IS NULL
如果你经常做这样的事情,你可能想要创建一个包含常量的永久表,例如
CREATE TABLE numbers (id int primary key);
INSERT INTO numbers (id) VALUES (0), (1), (2), ..., (1000);
然后你可以这样做:
SELECT t1.id
FROM numbers
JOIN MyTable t2
ON t1.id = t2.id
WHERE t1.id IN (1, 2, 3, 4, 5, 6)
AND t2.id IS NULL