4. 在3的基础上实现关联查询users表和products表。
时间: 2024-10-10 19:06:48 浏览: 20
day19--mysql多表查询1
如果你想从订单表`orders`同时查询相关的用户信息(`users`)和产品信息(`products`),可以使用`INNER JOIN`或者`LEFT JOIN`来连接这三个表,假设`users`表有`id`和`customer_id`字段,`products`表有`product_id`和`name`字段。这里是一个示例,基于`orders`表里的`customer_id`和`product_id`做关联查询:
```sql
SELECT o.id AS order_id, u.customer_name, p.product_name, o.status
FROM orders o
INNER JOIN users u ON o.customer_id = u.id
INNER JOIN products p ON o.product_id = p.product_id
WHERE o.status = 'your_status_value' AND u.customer_id IS NOT NULL -- 这里假设users表的id非空
ORDER BY o.id
LIMIT page_size OFFSET (page_number - 1) * page_size;
例如,查询状态为'已完成'的订单,显示用户名和产品名称:
SELECT order_id, customer_name, product_name, status
FROM (
SELECT o.*, u.customer_name, p.product_name
FROM orders o
INNER JOIN users u ON o.customer_id = u.id
INNER JOIN products p ON o.product_id = p.product_id
WHERE o.status = 'completed'
)
LIMIT 10 OFFSET 20;
```
这个查询首先会返回所有满足条件的订单,然后按照指定的页面范围分页展示。
阅读全文