如何内部连接表A + B和参考表A到多个其他表

时间:2013-09-04 09:53:36

标签: mysql

我目前正在使用以下内容成功地在表A + B之间进行OUTER JOIN:

SELECT * FROM player_img
  LEFT OUTER JOIN user_play
  ON player_img.player_img_id = user_play.user_play_entry_player_img_id
  AND user_play.user_play_uid = 1
  WHERE player_img.player_img_id IS null

这给了我表A中的所有结果,它没有来自表B的user_play_uid = 1

的任何引用

在表A中,我有引用其他表的属性 - 我也希望查询这些字段。一些表引用的快速示例:

TABLE_A:
player_img_id (unique key)
player_img_player_id (reference to: TABLE_C "player_id")
player_img_category_id (reference to: TABLE_D "category_id")

TABLE_B:
user_play_entry_player_img_id (reference to TABLE_A: "player_img_id")
user_play_uid (reference to table with user.id)

TABLE_C:
player_id (unique key)
player_country (reference to table with country.id)
player_league (reference to table with league.id)

TABLE_D:
category_id (unique key)

想想我可以沿着以下方式做一些事情(当然哪个方面根本不起作用)

SELECT u . * , up . * , pi . * , p . * , c . *
  FROM user u, user_play up, player_img pi, player p, country c
  LEFT OUTER JOIN up
  ON pi.player_img_id = up.user_play_entry_player_img_id
  WHERE pi.player_img_id IS null
  AND up.user_play_uid = $this->user_id
  AND pi.player_img_category_id = $this->category_id
  AND pi.player_img_player_id = p.player_id
  AND p.player_country = c.country_id

关于如何将我的OUTER JOIN与参考查找表结合起来的任何建议?

修改: 当前尝试使用以下建议 - 查询正在运行,但没有显示结果 - 提示?:/

SELECT u . * , up . * , pi . * , p . * , c . *
  FROM user u
  INNER JOIN player_img pi
  ON pi.player_img_category_id  = 3
  INNER JOIN player p
  ON pi.player_img_player_id    = p.player_id
  INNER JOIN country c
  ON p.player_country           = c.country_id
  LEFT OUTER JOIN user_play up
  ON pi.player_img_id = up.user_play_entry_player_img_id
  WHERE pi.player_img_id IS null
  AND up.user_play_uid      != 1

1 个答案:

答案 0 :(得分:0)

使用ANSI-92 JOIN语法而不是您正在使用的旧语法:

SELECT u . * , up . * , pi . * , p . * , c . *
FROM user u
INNER JOIN player_img     pi ON ...
INNER JOIN player          p ON pi.player_img_player_id = p.player_id
INNER JOIN country         c ON p.player_country        = c.country_id
LEFT OUTER JOIN user_play up ON pi.player_img_id    = up.user_play_entry_player_img_id
WHERE pi.player_img_id IS null
  AND up.user_play_uid = $this->user_id

注意事项:

  • 您的查询中没有条件说明如何JOIN使用表player_img pi和其他表格。

  • 条件AND up.user_play_uid = $this->user_id可能会删除由于LEFT JOIN而导致的未被捕获的行,在这种情况下,您可能需要将该条件移动到子查询而不是LEFT OUTER JOIN该表直接