SELECT b.allocated_quantity, b.choice_flag, detail.pur_content, detail.unit_price_including_tax, detail.unit_price_excluded_tax, detail.inquiry_item_id itemId, detail.rate*100 rate, detail.id detailId detail.rate * 100 rate, detail.id detailId FROM inquiry_evaluation_allocated_info a LEFT JOIN inquiry_evaluation_allocated_info b ON a.evaluation_id = b.evaluation_id AND a.supplier_code = b.supplier_code LEFT JOIN inquiry_offer_detail detail ON b.offer_detail_id = detail.id WHERE a.id = #{allocatedId} and a.last_flag=1 and b.last_flag=1 WHERE a.id = #{allocatedId} and a.last_flag = 1 and b.last_flag = 1 检查这段sql有什么问题,能否优化
时间: 2024-02-14 11:17:58 浏览: 64
这段 SQL 语句有以下问题:
1. WHERE 子句出现了两次,且条件相同,应该将两个 WHERE 子句合并为一个。
2. 没有为查询结果指定表别名,可能会导致查询结果中的列名冲突。
3. 只有一个表的字段被查询,可以不使用 LEFT JOIN,而使用 INNER JOIN。
以下是优化后的 SQL 语句:
```
SELECT b.allocated_quantity,
b.choice_flag,
detail.pur_content,
detail.unit_price_including_tax,
detail.unit_price_excluded_tax,
detail.inquiry_item_id itemId,
detail.rate * 100 rate,
detail.id detailId
FROM inquiry_evaluation_allocated_info a
INNER JOIN inquiry_evaluation_allocated_info b
ON a.evaluation_id = b.evaluation_id
AND a.supplier_code = b.supplier_code
AND b.last_flag = 1
LEFT JOIN inquiry_offer_detail detail
ON b.offer_detail_id = detail.id
WHERE a.id = #{allocatedId}
AND a.last_flag = 1
```
在优化后的 SQL 语句中,将两个 WHERE 子句合并为一个,并使用 INNER JOIN 替换了 LEFT JOIN,同时为查询结果指定了表别名,可以更加清晰和简洁地表达查询逻辑。
阅读全文