我有这个查询:
SELECT
t1.team_flag AS flag_1,
t2.team_flag AS flag_2,
t1.team_name AS team_name_1,
t2.team_name AS team_name_2,
t1.team_id AS team_id_1,
t2.team_id AS team_id_2,
games.game_id,
games.game_team_1,
games.game_team_2,
games.game_time,
games.game_day,
games.game_location,
games.game_group,
games.game_active,
location_id_to_names.location_id,
location_id_to_names.location_name
FROM games
LEFT JOIN teams t1 ON t1.team_id = game_team_1
LEFT JOIN teams t2 ON t2.team_id = game_team_2
LEFT JOIN location_id_to_names ON games.game_location = location_id_to_names.location_id
ORDER BY games.game_day
这将返回所有团队名称正确的所有游戏,但是,我现在只想选择具有特定 ID 的一场游戏,但这是行不通的:
SELECT
t1.team_flag AS flag_1,
t2.team_flag AS flag_2,
t1.team_name AS team_name_1,
t2.team_name AS team_name_2,
t1.team_id AS team_id_1,
t2.team_id AS team_id_2,
games.game_id,
games.game_team_1,
games.game_team_2,
games.game_time,
games.game_day,
games.game_location,
games.game_group,
games.game_active,
location_id_to_names.location_id,
location_id_to_names.location_name
FROM games
LEFT JOIN teams t1 ON t1.team_id = game_team_1 AND games.game_id = :game_id
LEFT JOIN teams t2 ON t2.team_id = game_team_2
LEFT JOIN location_id_to_names ON games.game_location = location_id_to_names.location_id
ORDER BY games.game_day
(:game_id) 由 PDO 解析。
这是我得到的输出:
突出显示的行中的 ID 是正确的,但它不是第一行,我需要将其作为第一行,因为我想将搜索限制为 1 个结果,所以我不希望行填充空值.
完成此任务的最佳方法是什么?
最佳答案
将 games.game_id = :game_id 移至 WHERE 语句
SELECT
t1.team_flag AS flag_1,
t2.team_flag AS flag_2,
t1.team_name AS team_name_1,
t2.team_name AS team_name_2,
t1.team_id AS team_id_1,
t2.team_id AS team_id_2,
games.game_id,
games.game_team_1,
games.game_team_2,
games.game_time,
games.game_day,
games.game_location,
games.game_group,
games.game_active,
location_id_to_names.location_id,
location_id_to_names.location_name
FROM games
LEFT JOIN teams t1 ON t1.team_id = game_team_1
LEFT JOIN teams t2 ON t2.team_id = game_team_2
LEFT JOIN location_id_to_names ON games.game_location = location_id_to_names.location_id
WHERE
games.game_id = :game_id
ORDER BY games.game_day
关于php - SQL帮助,无法通过连接获得所需的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24055615/