2

我有 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 查询应该是什么样子吗?

谢谢

4

2 回答 2

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
于 2013-02-13T23:05:44.557 回答
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
)
于 2013-02-13T23:05:53.593 回答