我正在尝试将数据从另一个表 feed.tempXML 中插入表 feed.author 。我第一次执行这个语句时效果非常好,但是当我在 feed.tempXML 中添加数据并再次运行时,新作者没有被添加到 feed.author 表。 IF语句是否需要更改?
代码:
IF NOT EXISTS(SELECT DISTINCT t.author FROM feed.tempXML t
JOIN feed.author a ON a.author = t.author)
INSERT INTO feed.author(author)
SELECT DISTINCT author
FROM feed.tempXML
WHERE author IS NOT NULL
答案 0 :(得分:4)
您的查询中的问题是,在IF
条件下,您检查记录是否存在,但在插入时您没有这样做。
应该这样做
INSERT INTO feed.author
(author)
SELECT DISTINCT author
FROM feed.tempXML t
WHERE NOT EXISTS (SELECT 1
FROM feed.author a
WHERE a.author = t.author)
AND t.author IS NOT NULL
答案 1 :(得分:0)
如果我理解您的问题,为什么不使用EXCEPT
?
INSERT INTO feed.author (author)
SELECT author
FROM feed.tempXML
WHERE author IS NOT NULL
EXCEPT
SELECT author
FROM feed.author;
这将插入feed.tempXML
feed.author
用户
另外,如果记住'feed.tempXML'表中的'author'可以有空字符串(在理论上,可能在你的情况下不是),所以用IS NOT NULL
替换> ''
是明智的。所以查询变为:
INSERT INTO feed.author (author)
SELECT author
FROM feed.tempXML
WHERE author > ''
EXCEPT
SELECT author
FROM feed.author;