t-sql NOT IN 多列 [英] t-sql NOT IN with multiple columns
问题描述
我有一个 Microsoft SQL 数据库,我想在其中插入一些数据.我在 4 列上有一个唯一键,我想将多个表中的数据插入到该表中,同时检查数据以确保它不会违反键的唯一性.如果我在单列上这样做,我会做一个 NOT IN,就像这样..
I have a Microsoft SQL database, where i am trying to insert some data. I have a unique key on 4 columns and i want to insert data from multiple tables into this table while checking the data to make sure it will not violate the uniqueness of the key. If i was doing this on a single column, i would do a NOT IN, like so..
INSERT TABLE_A (FLD_1)
SELECT FLD_1
FROM TBL_B
INNER JOIN TBL_C
ON TBL_B.FLD_1 = TBL_C.FLD_1
WHERE TBL_B.FLD_1 NOT IN
(
SELECT TBL_A.FLD_1 FROM TBL_A
)
有什么想法吗?
推荐答案
请改用 NOT EXISTS,因为您必须处理多个列.
Use NOT EXISTS instead since you have to deal with multiple columns.
http://www.techonthenet.com/sql/exists.php
未经测试,但大致如下:
Untested, but roughly it will be this:
SELECT FLD_1
FROM TBL_B
INNER JOIN TBL_C ON TBL_B.FLD_1 = TBL_C.FLD_1
WHERE NOT EXISTS
(
SELECT TBL_A.FLD_1 FROM TBL_A INNER JOIN TBL_B ON TBL_B.FLD1 = TBL_A.FLD1
)
对于多列检查,大致如下:
For a multi-column check it would be roughly this:
SELECT FLD_1, FLD_2, FLD_3, FLD_4)
FROM TBL_B
INNER JOIN TBL_C ON TBL_B.FLD_1 = TBL_C.FLD_1
WHERE NOT EXISTS
(
SELECT TBL_A.FLD_1, TBL_A.FLD_2, TBL_A.FLD_3, TBL_A.FLD_4
FROM TBL_A
INNER JOIN TBL_B ON TBL_B.FLD1 = TBL_A.FLD1 AND
TBL_B.FLD2 = TBL_A.FLD2 AND
TBL_B.FLD3 = TBL_A.FLD3 AND
TBL_B.FLD4 = TBL_A.FLD4
)
这篇关于t-sql NOT IN 多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!