[英]SQL: What is the best way to select rows from a table that do not exist in another table only with a particular id?
I use the Informix database where I have 2 tables artind and coord that have relationship with one another, key_code and cm_key_coord_code 我使用Informix数据库,其中有2个表artind和coord相互关联, key_code和cm_key_coord_code
table artind 表artind
+-----------+-------------+
| Field | Type |
+-----------+-------------+
| key_code | char(8) |
| descr | char(30) |
+-----------+-------------+
table coord 表坐标
+--------------------+-------------+
| Field | Type |
+--------------------+-------------+
| cm_key_coord_code | char(8) |
| cm_t_coor | int |
| descr_coord | char(30) |
+--------------------+-------------+
Usually to select all record in table artind that not have a record with same code ( key_code equal to cm_key_coord_code ) and cm_t_coor = 2 in table coord I use: 通常在表artind中选择所有不具有相同代码(key_code等于cm_key_coord_code)且表coord中的cm_t_coor = 2的记录的记录,我使用:
select * from artind where
key_code not in (select cm_key_coord_code from coord
where cm_t_coor = 2);
There is a better way? 有一个更好的方法?
Your method is fine, but not recommended. 您的方法很好,但不建议这样做。 If any
cm_key_coord_code
values are NULL
, then no records will be selected. 如果任何
cm_key_coord_code
值为NULL
,则不会选择任何记录。 That is how NOT IN
is defined, but not usually what is intended. 这就是
NOT IN
的定义方式,但通常不是所要的。
I advise either NOT EXISTS
or LEFT JOIN
: 我建议
NOT EXISTS
或LEFT 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
);
or: 要么:
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;
i don't think there is a better way than yours. 我认为没有比您更好的方法了。 i can give you a different one, but ultimately this will likely be translated to the same operations from the query-engine.
我可以给您一个不同的选项,但是最终它很可能会转换为查询引擎中的相同操作。 you query actually might be more performant.
您的查询实际上可能更高效。
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
if you have performance problems with yours i suggest looking at the indexes on the tables 如果您遇到性能问题,建议您查看表上的索引
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.