gpt4 book ai didi

Mysql JOIN(多个)表

转载 作者:行者123 更新时间:2023-11-29 02:01:00 26 4
gpt4 key购买 nike

我有 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 |
+-------------------------------+

我正在尝试将所有 JOIN 合并到一张表中,它应该如下所示:

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

知道 sql 查询应该是什么样子吗?

谢谢

最佳答案

尝试合并:

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)只有一行,您可以对每个查询使用限制/分组依据/排序依据(假设您有日期列):

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

关于Mysql JOIN(多个)表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14864933/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com