我需要完成这个MySQL多表JOIN

时间:2010-10-28 15:40:21

标签: mysql

我有entiresequipmentsbrandstimesseasons

  • ID
  • 时间
  • equipment_1
  • equipment_2

设备

  • ID
  • id_brand

品牌

  • ID
  • 名称

  • ID
  • id_season

季节

  • ID
  • 名称

我的实际SQL查询是:

SELECT entries.*, times.id_season AS id_season
FROM entries, seasons
WHERE entries.time = times.id

但在最后的查询中,我需要下一个我不知道如何获取它的信息:

  1. 每个条目的名称.quipment_为equipment_1_name和equipment_2_name,在brands.name中设置。
  2. 赛季名称为season_name。
  3. 提前谢谢!

1 个答案:

答案 0 :(得分:2)

假设您已将数据标准化。这避免了昂贵的笛卡尔连接。我自己从不使用笛卡尔连接,尽管在某些情况下它们是有用的。不过这里不是。

SELECT
  entries.*,
  times.id_seasons AS id_season,
  b1.name AS equipment_1_name,
  b2.name AS equipment_2_name,
  seasons.name AS season_name
FROM entries
LEFT JOIN equipments AS equipments_1
  ON equipments_1.id = entries.equipment_1
LEFT JOIN brands AS brands_1 
  ON brands_1.id = equipments_1.id_brand
LEFT JOIN equipments AS equipments_2 
  ON equipments_2.id = entries.equipment_2
LEFT JOIN brands AS brands_2
  ON brands_2.id = equipments_2.id_brand
LEFT JOIN times 
  ON times.id = entries.time
LEFT JOIN seasons 
  ON seasons.id = times.id_season;