0

我需要为当前用户显示所有灯具(谁玩'反对'谁),所以我编写了 SQL 查询

SELECT 
  fixture.*
FROM
  sport_team_player AS team_player, sport_team AS team 
INNER JOIN sport_fixture AS fixture 
  ON (`team_player`.`team_id` = fixture.`team1_id` OR `team_player`.`team_id` = fixture.`team2_id`)
WHERE 
  team_player.`team_id` = team.`team_id` AND team_player.`player_id` = '16'

这不起作用并告诉我 team_player.team_id 不存在

但是如果我加入第二个表而不是从多个表中选择它就可以了。

PS。这不是编写此类查询的最佳方式,但它是由 ORM 模块生成的。

编辑:

结果将是夹具数据列表,例如

------------------------------
|fixture_id|team1_id|team2_id|
------------------------------
|1         | 2      | 3      |
------------------------------
4

3 回答 3

2

试试这个。应该导致与您的查询相同的查询;

SELECT fixture.*
FROM  sport_team_player AS team_player
JOIN  sport_team AS team 
ON    team_player.`team_id` = team.`team_id` AND team_player.`player_id` = '16'
INNER JOIN sport_fixture AS fixture 
ON (`team_player`.`team_id` = fixture.`team1_id` 
     OR `team_player`.`team_id` = fixture.`team2_id`) 

在建立连接时,您不应该混淆这两种表示法。您用于加入 team_player 和 team 的逗号,以及随后对内部加入的调用,很可能会触发未知列错误。

于 2013-10-08T08:23:00.647 回答
0

例如:

SELECT f.*
  FROM sport_team_player p
  JOIN sport_team t
    ON t.team_id = p.team_id 
  JOIN sport_fixture f
    ON p.team_id IN(f.team1_id,f.team2_id)
 WHERE p.player_id = 16;
于 2013-10-08T08:41:40.470 回答
0

逗号运算符的优先级小于 INNER JOIN、CROSS JOIN、LEFT JOIN。这就是为什么当您将逗号与其他连接表运算符混合使用时 [Unknown column 'col_name' in 'on Clause'] 会发生错误。如果您指定交叉联接(以获取前两个表的笛卡尔积)而不是逗号,则相同的查询将起作用,因为在 from 子句中,表运算符将从左到右进行评估:

SELECT 
    fixture.*
FROM
    sport_team_player AS team_player
    cross join sport_team AS team 
    INNER JOIN sport_fixture AS fixture 
    ON (team_player.team_id = fixture.team1_id OR team_player.team_id = fixture.team2_id)
WHERE 
  team_player.team_id = team.team_id AND team_player.player_id = '16'
于 2013-10-08T08:37:25.623 回答