2012-09-07 11 views
24

Ho questa tabella in MySQL, per esempio:MySQL ottenere gli ID mancante dalla tabella

ID | Name 
1 | Bob 
4 | Adam 
6 | Someguy 

Se si nota, non esiste un numero ID (2, 3 e 5).

Come posso scrivere una query in modo che MySQL risponda solo agli ID mancanti, in questo caso: "2,3,5"?

risposta

14

Un altro interrogazione efficiente:

SELECT (t1.id + 1) as gap_starts_at, 
     (SELECT MIN(t3.id) -1 FROM my_table t3 WHERE t3.id > t1.id) as gap_ends_at 
FROM my_table t1 
WHERE NOT EXISTS (SELECT t2.id FROM my_table t2 WHERE t2.id = t1.id + 1) 
HAVING gap_ends_at IS NOT NULL 
+0

Grazie Ivan. Funziona così molto più veloce! – MikeC

+0

Questo ha funzionato per me, tranne che ha perso il gap iniziale a partire da id = 1 – egprentice

2

Sopra query darà due colonne in modo da poter provare questo per ottenere i numeri mancanti in una singola colonna

select start from 
(SELECT a.id+1 AS start, MIN(b.id) - 1 AS end 
    FROM sequence AS a, sequence AS b 
    WHERE a.id < b.id 
    GROUP BY a.id 
    HAVING start < MIN(b.id)) b 
UNION 
select c.end from (SELECT a.id+1 AS start, MIN(b.id) - 1 AS end 
    FROM sequence AS a, sequence AS b 
    WHERE a.id < b.id 
    GROUP BY a.id 
    HAVING start < MIN(b.id)) c order by start; 
+0

Con questa versione a una colonna, ottengo (per esempio) '475',' 477', '506',' 508', '513 'ma con la versione a due colonne, mi viene il' [475,475] ',' [477,506] ',' [508,513] 'che mi dice che mi mancano i numeri 475, 477-506 e 508-513. –

1

Per aggiungere un po 'alla risposta di Ivan, è la versione mostra i numeri mancanti all'inizio se 1 non esiste:

SELECT 1 as gap_starts_at, 
     (SELECT MIN(t4.id) -1 FROM testtable t4 WHERE t4.id > 1) as gap_ends_at 
FROM testtable t5 
WHERE NOT EXISTS (SELECT t6.id FROM testtable t6 WHERE t6.id = 1) 
HAVING gap_ends_at IS NOT NULL limit 1 
UNION 
SELECT (t1.id + 1) as gap_starts_at, 
     (SELECT MIN(t3.id) -1 FROM testtable t3 WHERE t3.id > t1.id) as gap_ends_at 
FROM testtable t1 
WHERE NOT EXISTS (SELECT t2.id FROM testtable t2 WHERE t2.id = t1.id + 1) 
HAVING gap_ends_at IS NOT NULL; 
Problemi correlati