在MySQL中嵌套select语句

时间:2013-04-15 09:47:37

标签: mysql database jdbc

我是关系型数据库的新手...... 我想列出同一个DB中许多表中的所有数据。

我有一个包含其他表的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。 我想要一个select * from CarKeys

中所有表的SELECT * FROM (SELECT * FROM CarKeys);命令

我试过这个:
       ERROR 1248 (42000): Every derived table must have its own alias

但是我收到了一条错误消息:
       WebApp

如何获取此数据库中所有表的所有信息?我使用的架构的名称是{{1}}

3 个答案:

答案 0 :(得分: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      |
+------------+---------+--------+--------+

答案 1 :(得分:1)

这个表没有很好的关系,你可以尝试:

SELECT * FROM Audi
UNION
SELECT * FROM Honda

结果:

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

答案 2 :(得分:0)

您必须使用存储过程

使用循环,将Carkeys.Name存储在variable (v1)

现在使用 Prepared Statement

执行
select * from v1