从多个表中选择与JOIN相比

时间:2013-10-08 08:17:33

标签: mysql sql

我需要显示当前用户的所有灯具(谁扮演'反对'谁)所以我写了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      |
------------------------------

3 个答案:

答案 0 :(得分: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和团队的逗号,以及随后对内部联接的调用,很可能会触发未知的列错误。

答案 1 :(得分:0)

逗号运算符的优先级小于INNER JOIN,CROSS JOIN,LEFT JOIN。这就是为什么当您将逗号与其他连接表运算符混合时[出现'on clause'中的未知列'col_name']错误。如果您指定交叉连接(以获取前两个表的笛卡尔积)而不是逗号,则相同的查询将起作用,因为在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'

答案 2 :(得分:0)

E.g:

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;