php - SQL帮助,无法通过连接获得所需的输出

标签 php mysql

我有这个查询:

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 解析。

这是我得到的输出:

enter image description here 突出显示的行中的 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/

相关文章:

php - 我正在尝试创建动态表,其中将获取数据并且我可以编辑我想要的任何值

php - 将字符串拆分为带有瑞典字符的单词

php - 如何在不使用 J 安装管理器的情况下通过复制文件来安装 Joomla 2.5 组件

java - 从 MySQL 中检索部分数据的数据

php - 执行此 UPDATE 查询的最佳方法

php - PDO beginTransaction 在两个单独的脚本中

mysql - MySQL/Django 中的部分空日期

php - Laravel 路由 : How to create a link to a PDF file

php - Yii2:如何根据前几页的总和在页脚中添加总和?

php - 从 PHP 中的 URL 字符串生成有效的数组键