优化 SELECT a.item_id, a.item_code, a.item_name, GROUP_CONCAT(b.channel_class_code) channelClassCodes, (SELECT count(*) FROM `tb_user_collection` where user_id = #{skuGoodDto.userId} and target_id = a.item_code) AS isCollect FROM osy_item AS a LEFT JOIN osy_item_sale AS b ON a.item_id = b.item_id where a.usable = 2 and b.usable = 2 and (b.channel_class_code = 10 or b.channel_class_code = 22) GROUP BY a.item_id
时间: 2024-04-15 14:30:39 浏览: 107
根据您提供的 SQL 查询语句,可以对其进行一些优化。首先,可以使用 IN 关键字来简化 WHERE 子句中的多个条件判断,将
```sql
(b.channel_class_code = 10 or b.channel_class_code = 22)
```
修改为
```sql
b.channel_class_code IN (10, 22)
```
接下来,可以使用 LEFT JOIN 连接 osy_item 和 osy_item_sale 表,然后再使用 GROUP BY 子句对结果进行分组。这样可以避免在 SELECT 子查询中使用子查询。
下面是优化后的 SQL 查询语句:
```sql
SELECT a.item_id,
a.item_code,
a.item_name,
GROUP_CONCAT(b.channel_class_code) AS channelClassCodes,
COUNT(c.target_id) AS isCollect
FROM osy_item AS a
LEFT JOIN osy_item_sale AS b ON a.item_id = b.item_id
LEFT JOIN tb_user_collection AS c ON c.target_id = a.item_code AND c.user_id = #{skuGoodDto.userId}
WHERE a.usable = 2
AND b.usable = 2
AND b.channel_class_code IN (10, 22)
GROUP BY a.item_id;
```
请注意,上述 SQL 查询语句中的 `#{skuGoodDto.userId}` 是占位符,您需要根据实际情况将其替换为相应的用户 ID 值。
阅读全文