我有一个ID列表(1,2,3,4,5,6)。我想知道表中不存在多少这些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这些不在表中
答案 0 :(得分:3)
试试这个:
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
答案 1 :(得分:3)
这将返回列表中不在表中的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