php - MySQL - 为什么这个 SELECT 查询会给出多条记录

标签 php mysql

我正在刷新一些 MySQL 技能(希望如此)。

我有这个问题:

SELECT stops.name, 
    stops.stop_id,  
    stop_times.trip_id,
    stop_times.departure_time,
    trips.route_id
FROM stops, routes, stop_times, trips
WHERE stops.stop_id = stop_times.stop_id AND trips.route_id = 2 AND stop_times.trip_id = 'SCHED255'
ORDER BY stops.stop_id ASC

这会返回正确的信息,但我得到了每条记录的多次出现。有什么想法我想念的吗?时间差

最佳答案

您在 FROM 子句中有 4 个表。因此,您至少需要 3 个 JOINS 以避免多次出现数据。

基本规则:n 个表 = (n-1) 个 JOINS。

+++++++++++编辑++++++++++++

在你的情况下它应该是这样的:

/*WITH EXCPLICIT JOINS*/
SELECT stops.name, stops.stop_id, stop_times.trip_id, stop_times.departure_time, trips.route_id
FROM stops s JOIN routes r ON s.col_name = r.col_name /*col_name is the name of the column that is defined as Contraint between these two*/
             JOIN stop_times st ON st.stop_id = s.stop_id
             JOIN trips t ON t.route_id = r.route_id
    AND t.route_id = 2 
    AND st.trip_id = 'SCHED255'
ORDER BY s.stop_id ASC

/*THE SAME THING WITH IMPLICIT JOINS*/
SELECT stops.name, stops.stop_id, stop_times.trip_id, stop_times.departure_time, trips.route_id
FROM stops AS s, routes AS r, stop_times AS st, trips AS t
WHERE s.col_name = r.col_name /*JOIN of stops and trips*/
    AND st.stop_id = s.stop_id /*JOIN of stop_times and stops*/
    AND t.route_id = r.route_id /*JOIN of trips and rutes*/
    AND t.route_id = 2 /*Other condition*/
    AND st.trip_id = 'SCHED255' /*Other condition*/
ORDER BY s.stop_id ASC

关于php - MySQL - 为什么这个 SELECT 查询会给出多条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33453980/

相关文章:

php - 在 Symfony 1.4 中订购嵌入式表单

php - 如果在mysql数据库中插入和更新查询期间数据类型不匹配,如何跟踪错误?

php - 我需要使用 html 中的 select 发送 id

java - 如何通过java连接正确的MySQL "desc table"

mysql - 根据另一个表的聚合结果更新表

php - 我想进行查询,从多个表中检索多个列

php - 具有多个条件的 SQL 更新

phpmyadmin html 连接

LocalHost 上的 PHP 连接被拒绝 (HY000/2002)

mysql - 我真的必须创建一个临时表吗?