使用MySql并需要选择(并稍后插入)temp_comments中的数据到注释中 - 除非注释表中已存在注释。以下是一些示例的测试数据
comments table
id | apn | account | comment
--------------------------------
1 | 100 | | todays comment
2 | 101 | | yesterdays comment
3 | 109 | | todays comment
4 | 122 | | more comments
5 | | 34550 | todays comment
6 | | 12433 | another comment
temp_comments table
id | apn | account | comment
-----------------------------------------
1 | 92 | | todays comment
2 | 99 | | another comment
3 | 100 | | more comments
4 | 109 | | todays comment
5 | | 34588 | new comment
在这种情况下,应该选择temp_comments中除id#4以外的所有内容并将其插入注释中(因为该记录, apn | account | comment 都匹配注释表中的一行)。 / p>
我尝试在尝试插入之前使用select语句:
select apn, account, comment
from temp_comments
where not exists( select apn, account, comment
from temp_comments
except
select apn, account, comment
from comments)
由于EXCEPT在mySQL中不起作用,因此会弹出错误。不知道如何使用连接,因为它需要匹配我想要排除它的所有3个字段。一旦我开始使用SELECT,我就需要插入注释,例如:
INSERT into comments
apn, account, comments
SELECT (and put my working SELECT statement HERE)
答案 0 :(得分:2)
使用LEFT JOIN
查找一个表格中与另一个表格不匹配的所有行。
SELECT tc.apn, tc.account, c.comment
FROM temp_comments AS tc
LEFT JOIN comments AS c ON c.apn <=> tc.apn AND c.account <=> tc.account AND c.comment <=> tc.comment
WHERE c.id IS NULL
或NOT EXISTS
:
SELECT apn, account, comment
FROM temp_comments AS tc
WHERE NOT EXISTS
(SELECT *
FROM comments AS c
WHERE c.apn <=> tc.apn AND c.account <=> tc.account AND c.comment <=> tc.comment)
答案 1 :(得分:0)
根据@ Barmar的建议,我发布了我的答案,而不是仅仅将其作为原始问题的编辑。另外,@ barmar在11-20-Comment CONCAT上与1-120-Comment相同,所以我进行了编辑以防止这种情况发生。
要进行选择 - 只需连接字段并将所有3个字段与另一个字段进行比较。注意:如果没有值,则必须添加IFNULL以获得正确的结果,因为apn或帐户为空 - 在我列出的表中不清楚。这是我用于SELECT的代码:
select tc.apn, tc.account, tc.comment
from temp_comments tc
where
concat("apn",IFNULL(tc.apn ,''),"acct",IFNULL(tc.account ,''),"comment",tc.comment)
not in
(SELECT concat("apn",IFNULL(c.apn ,''),"acct",IFNULL(c.account ,''),"comment",c.comment)
from comments c)