我有4个表orders
,users
,purchaseds
和cities
users
和purchaseds
包含字段{{1} }作为city_id
的外键,所以我想创建一个Join以获取所有表格内容,问题是cities
和users
包含不同的purchaseds
值,这意味着我不能为每个表获得city_id
(city_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
+---------------+---------+----------+-----+
请帮助!!
答案 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