使用带有select的create table在表之间复制数据

时间:2012-06-27 07:25:37

标签: mysql

我有aitisi(id,name1,surname1,father1,birthdate1,name2,surname2,father2,birthdate2 ...到5,费用,开始,到期,计划,地址,电话,城市,邮编)我想要将surnameX,nameX,fatherX,birthdateX(X = 1到5)列复制到新的表成员(id,tid,name,surname,father,birthdate),其中tid是table1.id的查找键。

我尝试使用MySQL,但没有把它弄好,所以我终于用PHP做了id:

$query_aitisi = "SELECT * FROM aitisi order by id asc";
$aitisi = mysql_query($query_aitisi, $connection) or die(mysql_error());
$row_aitisi = mysql_fetch_assoc($aitisi);
$totalRows_aitisi = mysql_num_rows($aitisi);

do {
  for($i=1; $i<=5; $i++){
    if ($row_aitisi['on_te'.$i]<>'') { 
    $query_copy = "insert into members (symbid, name, surname, father, birthdate) 
    values ('".$row_aitisi[id]."','".$row_aitisi['surname'.$i]."','".$row_aitisi['name'.$i]."','".$row_aitisi['father'.$i]."','".$row_aitisi['birthdate'.$i]."')";
$copy = mysql_query($query_copy, $connection) or die(mysql_error());
    }
  }
} while ($row_aitisi = mysql_fetch_assoc($aitisi));

但是,我真的很想知道正确使用“create table as select”语句以备将来使用。任何人?谢谢!

1 个答案:

答案 0 :(得分:0)

以下查询应该可以正常工作

create table members (symbid, surname, name, father, birthdate)
    (select id, surname1, name1, father1, birthdate1 from aitisi where on_te1 != ''
    union all
    select id, surname2, name2, father2, birthdate2 from aitisi where on_te2 != ''
    union all
    select id, surname3, name3, father3, birthdate3 from aitisi where on_te3 != ''
    union all
    select id, surname4, name4, father4, birthdate4 from aitisi where on_te4 != ''
    union all
    select id, surname5, name5, father5, birthdate5 from aitisi where on_te5 != '')