-1

我有一系列产品 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,或者可能有另一种很好的方法来进行此检查。你们觉得怎么样?

4

1 回答 1

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;

让我知道这是否需要更多解释。

于 2012-04-04T02:05:21.743 回答