gpt4 book ai didi

mysql - 如何使用sql从多个表中获取列

转载 作者:行者123 更新时间:2023-11-29 12:37:26 24 4
gpt4 key购买 nike

我从事铁路运输工作。我有下表:

日表

| - id  |  name  |
| 1 | sunday |
| 2 | monday |
| 3 | tuesday|

车站表

|- id   | name  | 
| 1 | zaria |
| 2 | kano |
| 3 | minna |

路由表

| - id  | source_station_id | destination_station_id|
| 1 | 1 | 2 |
| 2 | 1 | 3 |
| 3 | 2 | 3 |
| 4 | 3 | 2 |
| 3 | 3 | 1 |

出发表

| route_id | day_id | departure_time |
| 1 | 2 | 07:00 hrs |
| 1 | 3 | 07:00 hrs |
| 3 | 2 | 15:30 hrs |

route_id、day_id、source_station_id、destination_station_id 都是分别从路线、日期和车站表引用的外键。

现在...我如何使用 sql 从这些表中获取数据..输出如下表所示。

| source | destination | day | departure_time |

最佳答案

您想要使用JOIN:

SELECT 
source.name AS source,
destination.name AS destination,
day.name AS day,
departure.time AS departure_time
FROM departure
JOIN station AS source
ON departure.source_station_id = source.id
JOIN station AS destination
ON departure.source_station_id = destination.id
JOIN day
ON departure.day_id = day.id
WHERE
# any specific criteria you may have, like:
departure.day_id = 1 # for a sunday

应该这样做。欲了解更多信息,请参阅MySQL JOIN Syntax

也就是说,这是一个非常标准的问题,看到它被否决我不会感到惊讶。

此外,从结构的角度来看,您最好将“日期”存储为DATETIME,并动态地将其与人类可读的日期字符串相互转换。

就目前情况而言,由于您只处理一周中的某一天,因此您无法区分本周和去年或去年。看看 this comment 的下半部分,我在这里开始谈论跨越时间段,并讨论 DATETIME 的使用。从性能和易用性角度来看,使用 native 数据类型是更好的选择。

关于mysql - 如何使用sql从多个表中获取列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26558951/

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