2013-04-15 170 views
0

我是關係數據庫的新手...... 我想在同一個數據庫中列出許多表中的所有數據。在MySQL中嵌套select語句

我有一個包含其他表的NAMES的表。就像這樣:

mysql> select * from CarKeys; 


+-------+ 
| Name | 
+-------+ 
| Audi | 
| Honda | 
+-------+ 


mysql> select * from Audi; 

+-------+---------+--------+ 
| Model | NumDoor | Colour | 
+-------+---------+--------+ 
| A4 | 4  | White | 
+-------+---------+--------+ 


mysql> select * from Honda; 
+------------+---------+--------+ 
| Model  | NumDoor | Colour | 
+------------+---------+--------+ 
| Civic  | 4  | White | 
| Civic  | 4  | White | 
| HomdaModel | 5  | Red | 
+------------+---------+--------+ 

但現在,我不希望被調用select * from Hondaselect * from Audi seperately。 我想,這將select * from命名CarKeys

我想這中所有表的一個命令:
SELECT * FROM (SELECT * FROM CarKeys);

,但我得到了這樣的錯誤消息:
ERROR 1248 (42000): Every derived table must have its own alias

我怎麼能得到所有此數據庫中所有表的信息?我正在使用的Schema的名稱是WebApp

+1

錯誤的數據庫設計 –

回答

1

這個表是沒有良好的合作關係,你可以嘗試:

SELECT * FROM Audi 
UNION 
SELECT * FROM Honda 

結果:

+------------+---------+--------+ 
| Model  | NumDoor | Colour | 
+------------+---------+--------+ 
| A4   | 4  | White | 
| Civic  | 4  | White | 
| Civic  | 4  | White | 
| HomdaModel | 5  | Red | 
+------------+---------+--------+ 
1

SQL設計中存在一個大問題。你不應該這樣稱呼桌子。爲什麼不爲你的汽車創建一張表並添加一個引用包含名字的表的列?

+-------+-------+ 
| ID | Name | 
+-------+-------+ 
| 1  | Audi | 
| 2  | Honda | 
+-------+-------+ 



+------------+---------+--------+--------+ 
| Model  | NumDoor | Colour | Brand | 
+------------+---------+--------+--------+ 
| Civic  | 4  | White | 2  | 
| A4   | 4  | White | 1  | 
| Civic  | 4  | White | 2  | 
| HomdaModel | 5  | Red | 2  | 
+------------+---------+--------+--------+ 
0

你必須使用一個存儲過程

使用,在Carkeys.Name它保存在variable (v1)

現在執行使用Prepared Statement

select * from v1