Mysql JOIN(多个)表

时间:2013-02-13 23:01:02

标签: mysql

我有3张桌子。其中2个是相同的(相同的列,不同的数据),第三个有关于其他的一些信息数据2.数据库看起来像这样:

表1:

+--------------+
|  ID | Name   |
+--------------+
| 1  | Table 2 |
| 2  | Table 3 |
+--------------+

表2:

+-------------------------------+
| Name | Temperature | Pressure |
+-------------------------------+
| Table 2 |    22    | 1013     |
+-------------------------------+

表3:

+-------------------------------+
| Name | Temperature | Pressure |
+-------------------------------+
| Table 3 |    20    | 1009     |
+-------------------------------+

我正在尝试将所有内容加入到一个表中,它应该如下所示:

+-------------------------------+
| Name | Temperature | Pressure |
+-------------------------------+
| Table 2 |    22    | 1013     |
| Table 3 |    20    | 1009     |
+-------------------------------+

知道sql查询应该如何?

由于

2 个答案:

答案 0 :(得分:3)

尝试结合:

SELECT table1.name, temperature, pressure 
FROM table1 inner join table2 ON
table1.name = table2.name
UNION
SELECT table1.name, temperature, pressure 
FROM table1 inner join table3 ON
table1.name = table3.name

编辑: 您可以从这些结果中进行另一个选择,然后您可以限制,分组或订购:

SELECT * FROM
(
    SELECT table1.name, temperature, pressure 
    FROM table1 inner join table2 ON
    table1.name = table2.name
    UNION
    SELECT table1.name, temperature, pressure 
    FROM table1 inner join table3 ON
    table1.name = table3.name
) as JoinedTable
LIMIT 0, 1

编辑2: 要从每个表(表2和表3)只有一行,您可以为每个查询使用limit / group by / order by(假设您有列日期):

SELECT table1.name, temperature, pressure 
FROM table1 inner join table2 ON
table1.name = table2.name
ORDER BY date DESC
LIMIT 0, 1
UNION
SELECT table1.name, temperature, pressure 
FROM table1 inner join table3 ON
table1.name = table3.name
ORDER BY date DESC
LIMIT 0, 1

答案 1 :(得分:0)

您可以使用UNION声明:

(
    SELECT Name, Temperature, Pressure
    FROM Table1 INNER JOIN Table2 ON Table1.Name = Table2.Name
)
UNION
(
    SELECT Name, Temperature, Pressure
    FROM Table1 INNER JOIN Table3 ON Table1.Name = Table3.Name
)