0

我正在尝试从同一个表中选择项目,重新组织数据,然后将数据作为新记录插入到同一个表中(基本上我正在为 DNS 获取“A”记录并将它们转换为“PTR”记录)。

问题是,如果存在三列,我不想创建记录 - 所以基本上,如果三列都存在(并且它们都必须存在,因为如果只有一个不匹配,那么它应该是插入数据库)然后我想阻止 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 存在于另一行(基于当前插入),那么我希望它跳过该单个插入并继续下一个插入,因为我不希望数据库中的相同记录。

4

2 回答 2

0

根据您要检查的 3 个字段对表执行 LEFT JOIN(假设您只对 PTR 类型的现有字段感兴趣),并且只选择不匹配的记录:-

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'
于 2013-06-26T11:04:25.777 回答
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)
于 2013-06-26T10:23:12.620 回答