有没有更好的方法返回sql表中没有的列表值?

xiozqbni  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(307)

我有一个像[3004203004213004223]这样的数字列表,还有一个表,所有值都在300000到400000之间(除了300422和300423)。我需要从表中没有的列表中返回第一个值,现在我使用下面的代码,但是它太慢了。

foreach ($notas as $tuple) {
    $key = $tuple[0];
    $value = $tuple[1];

    if ($value) {
        $res = $PDO2->query("SELECT DISTINCT Num_Nota FROM itensnfs WHERE Num_Nota='$value'");
        $counter_codes = ($res->rowCount());

        if($counter_codes == 0){
            echo "Value " .$value. " don't exist";
            die();          
        }
    }
}
uoifb46i

uoifb46i1#

可以枚举派生表中的值,然后使用 not exists 和聚合:

select min(v.num) num
from (
    select 300420 num
    union all select 300421
    union all select 300422
    union all select 300423
) v
where not exists (select 1 from itensnfs i where i.Num_Nota = v.num)

根据你的数据库,有更整洁的选择 union all 生成派生表。
一些数据库支持行构造函数 values() :

select min(v.num) num
from (values (300420), (300421), (300422), (300423)) v(num)
where not exists (select 1 from itensnfs i where i.Num_Nota = v.num)

mysql是一个值得注意的例外,但是最近的版本支持 values row() :

select min(v.num) num
from (values row (300420), row (300421), row (300422), row (300423)) v(num)
where not exists (select 1 from itensnfs i where i.Num_Nota = v.num)

相关问题