2014-08-28 70 views
1

如何從具有可變列的多個表創建表(聯合不能使用)?如何從多個表中選擇表來創建表?

mysql> select * from a; 
+------+------+ 
| id | name | 
+------+------+ 
| 1 | Ruby | 
+------+------+ 

mysql> select * from b; 
+------+------+ 
| pid | name | 
+------+------+ 
| 1 | Java | 
| 1 | C++ | 
+------+------+ 

我想要什麼......

+------+------+------+------+ 
| id | name | pid | bname| 
+------+------+------+------+ 
| 1 | Ruby |  |  | 
|  |  | 1 | C++ | 
|  |  | 1 | Java | 
+------+------+------+------+ 

我都試過了。

mysql> create table t as select * from a; # worked fine 
mysql> alter table t as select pid, name as bname from b; #didn't work 
+1

你爲什麼不能使用'union'? – 2014-08-28 11:00:57

+0

爲什麼你要這樣做呢? – Strawberry 2014-08-28 11:14:55

+0

@Strawberry:我希望它能達到我以前的問題http://stackoverflow.com/questions/25531279/how-do-i-reference-parent-table-in-a-multi-table-join – Bala 2014-08-28 11:41:41

回答

1

有沒有使用union問題,你只需要選擇null S作爲不在表中的列:

CREATE TABLE t AS 
SELECT id, name, null AS pid, null AS bname 
FROM a 
UNION ALL 
SELECT null, null, pid, bname 
FROM b 
1

創建新表,包含所有四列。然後

INSERT INTO t (id, name) SELECT * FROM a; 
INSERT INTO t (pid, bname) SELECT * FROM b; 

第一行會把一切從a在那裏,並保留其他兩個字段作爲NULL;第二個將從b做相應的事情。您可以在一個CREATE/UNION聲明中完成整個事情,但如果這是一次性操作,則可能更容易理解您正在做什麼,如果您像這樣分階段進行操作。

1

你可以在這個相當神祕的方式做到這一點:

select a.*, b.* 
from a left join 
    b 
    on 1 = 0 
union all 
select a.*, b.* 
from b left join 
    a 
    on 1 = 0; 

這是一種方式,在MySQL中實現的:

select a.*, b.* 
from a full outer join 
    b 
    on 1 = 0; 

但是,它需要一個union。如果你想避免union

create table ab as 
    select a.*, b.* 
    from a left join 
     b 
     on 1 = 0; 

insert into ab 
    select a.*, b.* 
    from b left join 
     a 
     on 1 = 0;