首页 > 解决方案 > SQL查询获取用户和订单数据

问题描述

我的应用程序中有 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

标签: mysqlsql

解决方案


如果您想为一个订单选择两个不同的用户,那么您应该将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

推荐阅读