我正在尝试从同一个表中选择项目,重新组织数据,然后将数据插入到与新记录相同的表中(基本上我正在为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存在于另一行(基于当前插入),那么我希望它跳过该单个插入并继续下一个插入,因为我做不想在数据库中使用相同的记录。
答案 0 :(得分: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)
答案 1 :(得分: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'