我有這個疑問:SQL幫助,不能得到所需的輸出,連接
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個結果,所以我不希望行中填充空值。
完成這件事的最好方法是什麼?
考慮提供適當的DDLs(和/或一個sqlfiddle)與期望的結果集合在一起。這就是說,你可以嘗試按「flag_1 IS NULL」排序 – Strawberry
我不太明白。您必須添加一個「LIMIT」子句才能獲得1個結果;但是如果你只想要你的例子的第二行,你就必須考慮一個'WHERE field IS NOT NULL'子句。 –
從你的連接中刪除'LEFT' - 你不需要它 - 你需要的只是一個直接連接。 –