SQL:从表中选择仅具有特定ID的另一个表中不存在的行的最佳方法是什么?

时间:2016-11-16 15:38:00

标签: sql informix

我使用Informix数据库,其中我有2个表 artind coord 彼此有关系, key_code cm_key_coord_code

artind

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

coord

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

通常选择表artind中没有记录的所有记录 相同的代码(key_code等于cm_key_coord_code)和cm_t_coor = 2 in table coord我用:

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

有更好的方法吗?

2 个答案:

答案 0 :(得分:3)

你的方法很好,但不推荐。如果任何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;

答案 1 :(得分:1)

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

Option Explicit

Sub TestEverySevenRow()

Dim CurCell As Range

For Each CurCell In ActiveWorkbook.ActiveSheet.Range("A7:G41, J7:NI41")

    ' current row is divided by 7, therefore it's a weekend
    If CurCell.Row Mod 7 = 0 Then

        ' for debug purpose only
        CurCell.Value = "Current Row divided by 7"

        ' the rest of your code goes here

    End If

Next

End Sub

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