为了账号安全,请及时绑定邮箱和手机立即绑定

有没有更好的方法返回不在表 Sql 中的列表值?

有没有更好的方法返回不在表 Sql 中的列表值?

PHP
慕尼黑的夜晚无繁华 2023-07-08 17:45:44
我有一个数字列表,例如 [300420,300421,300422,300423],以及一个包含从 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();                  }    }}
查看完整描述

1 回答

?
智慧大石

TA贡献1946条经验 获得超3个赞

您可以枚举派生表中的值,然后使用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)


查看完整回答
反对 回复 2023-07-08
  • 1 回答
  • 0 关注
  • 59 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信