Mysql 我们如何插入?“;来自多个记录的数据“;,从一张桌子到另一张桌子?
下面的命令用于将数据从一个表插入到另一个表中Mysql 我们如何插入?“;来自多个记录的数据“;,从一张桌子到另一张桌子?,mysql,sql,Mysql,Sql,下面的命令用于将数据从一个表插入到另一个表中 insert into school_record (phone_id) select phone_id from students where name="abc" order by phone_id asc; 但是,如果我想为“abc”、“def”、“ghi”等名称插入所有phone_id值,该怎么办 这就是如何在从多个记录中选择值后,将数据从一个表插入到另一个表中的方法?如果需要学生表的所有电话号码,只需执行以下操作: ins
insert into school_record (phone_id)
select phone_id from students where name="abc"
order by phone_id asc;
但是,如果我想为“abc”、“def”、“ghi”等名称插入所有phone_id值,该怎么办
这就是如何在从多个记录中选择值后,将数据从一个表插入到另一个表中的方法?如果需要学生表的所有电话号码,只需执行以下操作:
insert into school_record (phone_id) select phone_id from students order by phone_id asc;
只有WHERE子句限制记录的数量。成功
where Name = 'abc' or name = 'def' or name = 'ghi'
或
在()中使用-括号中列出需要插入的所有名称
insert into school_record (phone_id)
select phone_id
from students
where name in ('abc', 'def', 'ghi', ...)
;
或者,如果需要插入所有
insert into school_record (phone_id)
select phone_id
from students
;
如果要插入具有常量名称的数据,可以尝试以下操作:
insert into school_record (phone_id)
select phone_id from students where name in ("abc","def","xyz")
order by phone_id asc;
insert into school_record (phone_id)
select phone_id from students where name in (select name from tablename)
order by phone_id asc;
如果要为另一个表中包含的名称插入phone_id,请尝试以下操作:
insert into school_record (phone_id)
select phone_id from students where name in ("abc","def","xyz")
order by phone_id asc;
insert into school_record (phone_id)
select phone_id from students where name in (select name from tablename)
order by phone_id asc;
请参阅下面的“in”:
使用
IN()
就像在('abc','def'..)中的where name一样Zarah您应该阅读最后一段“order by”,即使是单列,也可能很重要。阅读“replication”的示例顺便说一句:orderby子句应该不是必需的。您应该将表数据视为无序集。您只能在select语句中按其一个或多个列对其进行排序。不,这里的select使用insert,select不能保证在不同的执行中返回相同的顺序,如果您存储的结果排序可能很重要(可能不是Zarah询问的示例,而是在一些复杂的数据库中)。因此,即使是单身,也要按重要顺序订购column@Grijesh乔汉:我不明白。这是一个insert语句,因此它只是将记录添加到表中的记录集。因此,没有必要通过订购。(如果有一个自动递增的ID,顺序会有所不同。但是,我仍然不认为这是一个好主意,因此给ID一个超出引用它的记录的意义。”啊,好吧,我不知道MySQL中的复制策略。因此,当使用复制时,在MySQL的insert select中使用order by还有一个可能的原因。(虽然我现在能想到的不使用order by的唯一问题是自动递增的ID,这在这里据说没有问题:。所以我想知道还有什么其他问题。)