SQL:从一个 table 中获取 select 行但在另一个 table 中不存在且仅具有特定 ID 的行的最佳方法是什么?

SQL: What is the best way to select rows from a table that do not exist in another table only with a particular id?

我使用 Informix 数据库,其中有 2 个 tables artindcoord 彼此有关系, key_codecm_key_coord_code

table artind

+-----------+-------------+
| Field     | Type        |
+-----------+-------------+
| key_code  | char(8)     |
| descr     | char(30)    |
+-----------+-------------+

table 坐标

+--------------------+-------------+
| Field              | Type        |
+--------------------+-------------+
| cm_key_coord_code  | char(8)     |
| cm_t_coor          | int         |
| descr_coord        | char(30)    |
+--------------------+-------------+

通常select所有记录在table artind中没有记录的 相同的代码( key_code 等于 cm_key_coord_code )和 cm_t_coor = 2 in table 我使用的坐标:

select * from artind where
key_code not in (select cm_key_coord_code from coord
where cm_t_coor = 2);

有更好的方法吗?

你的方法很好,但不推荐。如果任何 cm_key_coord_code 值为 NULL,则不会选择任何记录。这就是 NOT IN 的定义方式,但通常不是预期的那样。

我建议 NOT EXISTSLEFT JOIN:

select a.*
from artind a
where not exists (select 1
                  from coord c
                  where c.cm_t_coor = 2 and c.cm_key_coord_code = a.key_code
                 );

或:

select a.*
from artind a left join
     coord c
     on c.cm_t_coor = 2 and c.cm_key_coord_code = a.key_code
where c.cm_key_coord_code is null;

我认为没有比您的方法更好的方法了。我可以给你一个不同的,但最终这可能会从查询引擎转换为相同的操作。您查询实际上可能性能更高。

select artind.* from artind 
    left join coord on key_code = cm_key_coord_code and cm_t_coor = 2 
where cm_key_coord_code is null

如果您遇到性能问题,我建议您查看表上的索引