Select first unused id using mysql query

I have a list of identifiers in array format as follows

$ids = [10, 13, 16, 20, 25, 28, 34, 40, 45]; 

My table is written as follows

 id email 1 abc@gmail.com 2 xyz@yahoo.com 10 jhs@gmail.com 13 cds@gmail.com 15 gfh@gmail.com 20 dsf@gmail.com 

I want to compare this table with the $ ids array and get the first unused identifier.

In the above example, I expect the result 16 . I need an elegant way / request to find the same.

Thanks in advance!

+5
source share
6 answers
 <?php foreach($ids as $id){ $result = DB::table($table)->where('id', '=', $id)->get(); if($result && count($result){ continue; } echo 'First unused id :'. $id; break; } 

? >

+2
source

Say your emails table name and your Email model: use Eloquent to get identifiers, then get the difference between your $ids array and identifiers from db, finally select the first one:

 $dbIds = Email::lists('id'); $diff = array_diff($ids, $dbIds); $first = array_shift($diff); 
+2
source
 create table t1 (id int, email text); insert into t1 values (1, ' abc@gmail.com '), (2, ' xyz@yahoo.com '), (10, ' jhs@gmail.com '), (13, ' cds@gmail.com '), (15, ' gfh@gmail.com '), (20, ' dsf@gmail.com '); create table t2 (id int); insert into t2 values (10), (13), (16), (20), (25), (28), (34), (40), (45); select t2.id from t2 where t2.id not in (select id from t1) 

result

 16, 25, 28, 34, 40, 45 

Demo

UPDATE

if you say

 select min(t2.id) from t2 where t2.id not in (select id from t1) 

you get only 16 :)

+1
source
  $sql = 'SELECT field WHERE field IN ' . implode( ',', $ids) . ' );'; $result = $db->query($sql); $found = array(); while ($row = $result->fetch_assoc()) { $found[] = $row['field']; } 

then you can compare with your fields

 $not_found = array_diff($ids, $found); 
0
source

Not sure if elegant, but you can use a temporary table to store your array using ID in MySQL. Then you can query this temporary table with a limit of 1 and NOT IN in the list of identifiers you want to leave:

 CREATE TEMPORARY TABLE IF NOT EXISTS tmp_all_ids (`id` INT(11)); INSERT INTO `tmp_all_ids` (`id`) VALUES (2), (5), (3); SELECT `id` FROM `tmp_used_ids` WHERE `id` NOT IN (SELECT `id` FROM `table_with_used_ids`) LIMIT 1; 

So, create this query in your code, replacing the values ​​in INSERT INTO with a list of all IDs in $ ids using implode () or something like that.

0
source

First you can get an array of IDs from your database using

 SELECT GROUP_CONCAT(id) FROM tbl_name 

let's say you put the content returned in $ result, your ID array would be

 $db_ids = explode(',', $result); 

then you can just

 $diff = array_diff($ids, $db_ids); $first_unused_id = min($diff); 
0
source

All Articles