2013-06-26 60 views
0

我試圖從同一個表中選擇項目,重新組織數據,然後插入數據到新記錄相同的表(基本上我正在採取「 A「記錄DNS並將其轉換爲」PTR「記錄)。MySQL:插入選擇從一些獨特的值

問題是,如果三列存在,我不想創建記錄 - 所以基本上,如果三列全都存在(並且它們都必須存在,因爲如果只有一列不匹配,那麼它應該被插入到數據庫中)然後我想讓MySQL不要插入它。

這裏的表:

mysql> describe records; 
+-------------+----------------+------+-----+---------+----------------+ 
| Field  | Type   | Null | Key | Default | Extra   | 
+-------------+----------------+------+-----+---------+----------------+ 
| id   | int(11)  | NO | PRI | NULL | auto_increment | 
| domain_id | int(11)  | YES | MUL | NULL |    | 
| name  | varchar(255) | YES | MUL | NULL |    | 
| type  | varchar(10) | YES |  | NULL |    | 
| content  | varchar(64000) | YES |  | NULL |    | 
| ttl   | int(11)  | YES |  | NULL |    | 
| prio  | int(11)  | YES |  | NULL |    | 
| change_date | int(11)  | YES |  | NULL |    | 
+-------------+----------------+------+-----+---------+----------------+ 
8 rows in set (0.00 sec) 

下面的SQL我能得到工作,它的工作原理,只是沒有其他三個領域是「獨一無二」的檢查:

INSERT INTO records (domain_id,name,type,content,ttl,prio,change_date) SELECT domain_id AS domain_id, substring_index(content, '.', -1) AS name, 'PTR' AS type, concat(`name`, '.') AS content, ttl AS ttl, prio AS prio, unix_timestamp() AS change_date from records where type='A' 

基本上這裏唯一缺少的是,如果domain_id,name和content ALL存在於另一行(基於當前插入),那麼我希望它跳過該單個插入並繼續下一個插入,因爲我不想要相同的記錄在數據庫中。

回答

0

只需在where子句中添加條件就不存在這樣的行。例如:

INSERT INTO records (domain_id,name,type,content,ttl,prio,change_date) SELECT domain_id AS domain_id, substring_index(content, '.', -1) AS name, 
'PTR' AS type, concat(`name`, '.') AS content, ttl AS ttl, prio AS prio, unix_timestamp() AS change_date from records a where type='A' 
and not exists (select * from records b where a.domain_id = b.domain_id and a.name = b.name and a.content = b.content) 
+0

不幸的是,這也行不通。 – drewrockshard

0

做一個LEFT JOIN對基於要檢查(假定你只對類型PTR的現有油田感興趣),只選擇記錄的3個字段的表不匹配: -

INSERT INTO records (domain_id,name,type,content,ttl,prio,change_date) 
SELECT a.domain_id AS domain_id, 
    substring_index(a.content, '.', -1) AS name, 
    'PTR' AS type, 
    concat(a.`name`, '.') AS content, 
    a.ttl AS ttl, 
    a.prio AS prio, 
    unix_timestamp() AS change_date 
FROM records a 
LEFT OUTER JOIN records b 
ON a.domain_id = b.domain_id 
AND a.name = b.name 
AND a.content = b.content 
AND b.type = 'PTR' 
WHERE b.id IS NULL 
AND a.type = 'A' 
+0

這不起作用 - 它將數據庫中的所有內容都包含進去,然後在存在的情況下創建它。 – drewrockshard

+0

它不應該這樣做。它從記錄中選擇a作爲獲取所有現有的A型記錄,並將其與記錄作爲b連接,並用LEFT JOIN在b記錄中檢查PTR的類型。任何發現b記錄的地方都會被忽略 – Kickstart

+0

Kickstart:我有40行數據,每次運行這條語句,它都會增加40條數據 - 所以它沒有做正確的事情。 – drewrockshard