我有一个包含2列的表:
nid realm
1 domain_id
1 domain_site
2 domain_id
3 domain_id
我希望每个条目都有1个域名条目,1个域名网站。所以我想最终:
nid realm
1 domain_id
1 domain_site
2 domain_id
2 domain_site
3 domain_id
3 domain_site
如果我在PHP中执行此操作,我只需要遍历整个列表并在不存在时插入额外的行。不幸的是,我只有PHPmyAdmin访问此数据库。有没有办法在直接SQL中执行此操作?
(如果它有所不同:该表当前有大约3000行,其中我认为2000将需要插入额外的行。此外,这是一次性的事情所以它不需要优化/超级-slick。)
答案 0 :(得分:2)
INSERT IGNORE INTO `table`
SELECT `alt1`.`nid`, `alt2`.`realm`
FROM `table` AS `alt1`, `table` AS `alt2`
答案 1 :(得分:0)
我认为这样做会,但我现在没有地方进行测试,而且我已经习惯了Sql Server而不是MySQL:
INSERT INTO `table`
SELECT id.nid, r.realm
FROM (SELECT nid FROM `table` GROUP BY nid) id
CROSS JOIN (SELECT realm FROM `table` GROUP BY realm) r
LEFT JOIN `table` t ON t.nid=id.nid AND t.realm=r.realm
WHERE t.realm IS NULL
答案 2 :(得分:0)
insert into MyTable
(nid, realm)
select nid, 'domain_id'
from MyTable m where not exists (
select 1
from MyTable
where MyTable.nid = m.nid and realm = 'domain_id'
)
union all
select nid, 'domain_site'
from MyTable m where not exists (
select 1
from MyTable
where MyTable.nid = m.nid and realm = 'domain_site'
)
答案 3 :(得分:0)
如果你对(nid,realm)有一个UNIQUE约束,你可以这样做:
INSERT IGNORE INTO nidTable (nid, realm)
SELECT nid, 'domain_site'
FROM nidTable WHERE realm = 'domain_id';