共享字段mysql加入问题

时间:2014-04-02 18:20:14

标签: mysql

我有4个表ordersuserspurchasedscities userspurchaseds包含字段{{1} }作为city_id的外键,所以我想创建一个Join以获取所有表格内容,问题是citiesusers包含不同的purchaseds值,这意味着我不能为每个表获得city_idcity_name表中的字段)。我该如何解决?

订单

cities

用户

+--------+---------+x
| order_id| user_id |
+---------+---------+
| 2323    | 23      |
+---------+---------+

Purchaseds (更新)

  +--------+---------+x
  | user_id | city_id |
  +---------+---------+
  | 23      | 11      |
  +---------+---------+

城市

   +--------+---------------+-----------+-----+
   | purchased_id   | order_id | user_id| city_id
   +----------------+---------+---------+-----+
   | 2222           |  230390  | 23     | 11
   +---------------+---------+----------+-----+

请帮助!!

1 个答案:

答案 0 :(得分:1)

在查询中使用多个表别名多次连接同一个表。

SELECT *
FROM Orders AS o
INNER JOIN Users AS u
    ON u.user_id = o.order_id
INNER JOIN Cities AS u_c
    ON u_c.city_id = u.city_id
INNER JOIN Purchaseds AS p
    ON p.order_id = o.order_id
INNER JOIN Cities AS p_c
    ON p_c.city_id = p.city_id