选择不在数据库中的ID

时间:2012-04-04 01:36:23

标签: php mysql arrays select

我有一系列产品ID,我需要找到数据库中不存在的ID。当然,我可以这样做:

// IDs in database: 1, 2, 3, 4, 5.
$products = array(4, 5, 6, 7);

$in_db = $db->exec("SELECT `id` FROM `table` WHERE `id` IN (" . implode($products) . ");");    
$in_db_ids = array();

foreach($in_db as $i){
    $in_db_ids[] = $i['id'];
}

$missing = array_diff($products, $in_db_ids);

但这很漫长而且很无聊。我也想过这样的事情:

// this query would be generated with PHP using an implode or something
$query = "
    SELECT `t`.`id` as `missing`
    SELECT 4 as `id` UNION SELECT 5 UNION SELECT 6 UNION SELECT 7
    LEFT JOIN `table` USING(`id`)
    WHERE `missing` is NULL;
";
$missing = $db->exec($query);

但这太不优雅了。 我认为应该有一个正确的方法来编写SELECT x UNION SELECT y UNION SELECT z,或者可能有另一种不错的方法来进行此检查。 伙计们,你觉得怎么样?

1 个答案:

答案 0 :(得分:1)

要在MySQL数据库中执行此操作,您将需要一个表或临时表,其行数等于您正在扫描缺失空白的表中的最高索引。没有办法解决这个问题--MySQL总是在表中“循环”,它不是一个可以设置自己的循环的过程语言。

话虽这么说,如果您创建或拥有足够大小的表,您可以使用用户变量创建自然数序列。让我们调用大表bigtable(其中的列是什么并不重要 - 我们只需要一个列的名称 - 我使用'acolumn')。

set @row = 0;
select n from 
  (select @row := @row + 1 as n from bigtable) as t 
left join mytable on mytable.id = t.n 
where mytable.acolumn is null;

如果需要更多解释,请告诉我。