[英]Select rows from a table where row in another table with same id has a particular value in another column
[英]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个表artind和coord相互关联, key_code和cm_key_coord_code
表artind
+-----------+-------------+
| Field | Type |
+-----------+-------------+
| key_code | char(8) |
| descr | char(30) |
+-----------+-------------+
表坐标
+--------------------+-------------+
| Field | Type |
+--------------------+-------------+
| cm_key_coord_code | char(8) |
| cm_t_coor | int |
| descr_coord | char(30) |
+--------------------+-------------+
通常在表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);
有一个更好的方法?
您的方法很好,但不建议这样做。 如果任何cm_key_coord_code
值为NULL
,则不会选择任何记录。 这就是NOT IN
的定义方式,但通常不是所要的。
我建议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
);
要么:
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
如果您遇到性能问题,建议您查看表上的索引
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.