我可以用php
或其他语言来解决它但我渴望学习更多SQL。
有没有办法解决这个问题:
我有两个表(我无法更改结构),一个content
包含一些数据,另一个content_info
包含一些其他信息。它们是相关的:content.id = content_info.content_id
。
我想做什么:如果content_info
但content
中没有数据集,我想复制它,最后两个数据集的数量相同表。我试过这种方式,但不幸的是它不起作用:
...
BEGIN
(SELECT id, ordering FROM content;)
cont:LOOP
@cid = SELECT content_id FROM content_info WHERE content_id = (id)
IF @cid != (id) THEN
INSERT INTO content_info SET content_id = (id), ordering = (ordering)
ITERATE cont;
END IF;
END LOOP cont;
END
..
有人有想法,还是最后不可能?提前谢谢!
答案 0 :(得分:8)
您可以使用INSERT IGNORE
插入新行,但如果表中已有一行会导致重复输入错误,则不执行任何操作。
INSERT IGNORE INTO jos_content_frontpage (content_id, ordering)
SELECT id, ordering FROM jos_content
答案 1 :(得分:2)
好像您正在寻找INSERT ... SELECT语法。可以将任何选择插入到表中,并为数据格式化以匹配目标表。
此外,您的INSERT语法不正确,看起来您正在使用UPDATE语法。
INSERT INTO table (field1, field2, field3) VALUES ('1','2','3');
INSERT INTO table (field1, field2, field3) SELECT field1, field2, field3 FROM ...
答案 2 :(得分:1)
我将仅给出一个字段的示例,即id字段。你也可以添加其他字段:
insert into content_info(content_id)
select content.id
from content left outer join content_info
on (content.id=content_info.content_id)
where content_info.content_id is null
另一种方式
insert into content_info(content_id)
select content.id
from content
where not exists (
select *
from content_info
where content_info.content_id = content.id
)