SQL查询以获取用户和订单数据

时间:2018-12-12 13:58:44

标签: sql mysqli

我的应用程序中有2个表,需要按以下方式获取数据

(为方便起见,将使用简单的表结构)

表1:用户

user_id -> int
user_name -> varchar
user_location -> text

表2:订单

order_id -> int
sender_id -> int
receiver_id -> int
order_price -> decimal
created_at -> date

我需要获取订单价格和日期+发送者和接收者的名称和位置。我在下面的查询中尝试过,但没有返回任何内容:

SELECT
    orders.price ,
    (users.adress) AS senderLocation , 
    (users.adress) AS receiverLocation FROM orders
JOIN users ON orders.sender_id = users.id and orders.receiver_id = users.id

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

如果要为一个订单选择两个不同的用户,则应将orders表与user表连接两次。例如:

SELECT 
  orders.price , 
  (senders.adress) AS senderLocation , 
  (receivers.adress) AS receiverLocation FROM orders
JOIN users as senders ON orders.sender_id = senders.id 
JOIN users as receivers ON orders.receiver_id = receivers.id

答案 1 :(得分:1)

除非您的JOIN中没有sender_id = receiver_id,否则您的orders_table子句无法被填充。

您需要两个JOIN,一个给发送者,另一个给接收者:

SELECT 
    orders.price , 
    (users1.adress) AS senderLocation , 
    (users2.adress) AS receiverLocation 
FROM orders
INNER JOIN users AS users1 ON orders.sender_id   = users1.id 
INNER JOIN users AS users2 ON orders.receiver_id = users2.id