mysql - 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
解决方案
如果您想为一个订单选择两个不同的用户,那么您应该将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
推荐阅读
- python - 如何根据每个数据框中两个不同日期列的日期条件合并两个数据框?
- python - 如何使用汇总统计信息注释 seaborn PairGrid 对角线
- javascript - 如何修复 Select2 触发器更改?
- solidity - 错误:无法估算气体;交易可能会失败或可能需要手动限制气体 ERC721:转移不属于自己的代币”
- jmeter - JMeter:从json响应中提取值范围
- clio-api - Clio webhook 自定义字段
- arrays - 在用 Delphi 编写的 DLL 中使用数组
- ios - 如何在 Objective C IOS Native Module Completion 处理程序中调用 React Native 回调函数
- javascript - 如何根据Javascript中的值对数组的Map数组进行排序
- vue.js - Vue 3 Composition API - 类似标签的组件中的“子”数据