如何修正SQL查询以获取符合要求的Oils与Picking_history表数据?
修正SQL查询以获取目标结果
数据表结构
1. Oils表
| id | fullname | amount |
|---|---|---|
| 1 | Salma | 70 |
| 2 | Ali | 20 |
| 3 | adams | 40 |
2. Picking_history表
| id | oil_id | first | second | third | date |
|---|---|---|---|---|---|
| 1 | 3 | 5 | 10 | 25 | 11-2023 |
期望查询结果
| id | fname | amount | first | Second | thid |
|---|---|---|---|---|---|
| 1 | Salma | 70 | |||
| 2 | Ali | 20 |
当前使用的错误SQL
SELECT Packing_history.id, Oils.fullname, amount, Packing_history.first, Packing_history.second, Packing_history.third FROM Packing_history INNER JOIN Oils ON Packing_history oil_id != Oils.id WHERE Packing_history.date != '11-2023' GROUP BY Packing_history.id
问题分析与修正方案
你的SQL存在多处问题:
- 表名拼写错误:将
Picking_history误写为Packing_history - JOIN语法错误:关联条件
Packing_history oil_id != Oils.id缺少字段访问的点号,且INNER JOIN逻辑错误——它只会返回两张表都匹配的记录,无法筛选出无对应拣选记录的油品 - 逻辑偏差:原SQL的过滤条件和关联逻辑完全不符合需求,无法得到目标结果
修正后的SQL代码
SELECT o.id, o.fullname AS fname, o.amount, ph.first, ph.second, ph.third AS thid FROM Oils o LEFT JOIN Picking_history ph ON o.id = ph.oil_id AND ph.date = '11-2023' WHERE ph.id IS NULL
代码说明
- 用
LEFT JOIN以Oils表为主表,关联Picking_history表,关联条件限定为对应油品ID且拣选日期为'11-2023' - 通过
WHERE ph.id IS NULL过滤掉存在对应拣选记录的油品,仅保留无匹配的记录(即Salma和Ali) - 用
AS给字段设置别名,完全匹配目标结果中的fname和thid字段名
内容的提问来源于stack exchange,提问作者Ammar
相关产品推荐
相关产品推荐

