2016-04-06 41 views
1

使用MySql並需要從temp_comments中選擇(並稍後插入)數據到註釋中 - 除非註釋表中已存在註釋。下面是一個例子MySql加入2個沒有單個公共字段的表來排除記錄

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 

在這種情況下一些測試數據,所有除ID#4從temp_comments應選擇並插入註釋(因爲與記錄,APN |賬戶|評論所有匹配的行在評論表中)。

我試圖得到一個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) 

因爲除非不MySQL的工作,這會彈出一個錯誤。不知道如何使用連接,因爲它的所有3個字段需要匹配我想要排除它。一旦我得到了SELECT工作,我需要插入註釋,如:

INSERT into comments 
apn, account, comments 
SELECT (and put my working SELECT statement HERE) 

回答

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) 
+0

這實際上是從評論中獲得結果,而不是temp_comments。請注意我的編輯 - 我弄清楚如何在所有3個字段上使用CONCAT提取數據。 – pokerPro

+0

對不起,我剛把它們弄倒了。 – Barmar

+0

您應該將解決方案作爲答案發布,而不是編輯問題。 – Barmar

0

每@ Barmar的建議下,我張貼我的答案,而不是僅僅把它當作在我原來的問題編輯。此外,@ barmar在11-20評論中評論CONCAT與1-120評論相同,所以我做了一個編輯以防止這種情況發生。

要做選擇 - 只是concat字段並比較所有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) 
相關問題