插入两个选择并进行比较

时间:2017-07-05 08:27:00

标签: sql sql-server

在这个例子中看起来很愚蠢,但这就是我想要做的事情:

TABLE_A:

id    fk_b_id              full_name
1     [I want '10' here]   [I want 'John, Doe' here]

表-B:

id    first_name
10    John

Table_c:

id    full_name    date
20    John, Doe    2020-01-01

我得到的所有全名都不在c中,符合以下标准:

select distinct full_name
from Table_c
where full_name not in (
    select full_name
    from Table_a ) and date > GETDATE()

查询的结果应与Table_b的id(fk_b_id)一起插入Table_a。因此,我需要在Table_a的full_name和Table_b的first_name之间进行比较,以获得正确的fk。我可以像这样做比较:

where Table_b.first_name = LTRIM(RTRIM(RIGHT(Table_c.full_name, CHARINDEX(',', REVERSE(Table_c.full_name))-1 )))

我可以将表c中的所有全名(符合条件)和表b中的fk(其名字匹配)插入到一个查询中的表a中吗?

1 个答案:

答案 0 :(得分:1)

当然,只需使用您的条件在表B和C之间加入

INSERT INTO Table_a (fk_b_id, full_name)
SELECT DISTINCT b.id, c.full_name 
FROM Table_c c
INNER JOIN Table_b b ON b.first_name = LTRIM(RTRIM(RIGHT(c.full_name, CHARINDEX(',', REVERSE(c.full_name))-1 )))
WHERE c.full_name not in (
    select a.full_name
    from Table_a a ) and c.date > GETDATE()

编辑:

另请注意,如果您的table_a.full_name列可以包含NULL值,则NOT IN子查询将无法为您提供预期结果。我建议重写它以使用NOT EXISTS

WHERE NOT EXISTS 
  (SELECT * FROM Table_a WHERE Table_a.Full_Name = Table_c.FUll_Name )