SELECT A.ID, A.TITLE, A.CLASSIFY_ID, B.CLASSIFY_NAME, A.CREATED_BY_ENTERPRISE_NAME, A.CREATED_BY_NAME, A.CREATED_TIME, A.SHOW_STATUS_ID, A.SHOW_STATUS, A.STATUS_ID, C.STATUS, A.IS_TOP FROM T_INFORMATION_INFO AS A LEFT JOIN T_INFORMATION_CLASSIFY AS B ON A.CLASSIFY_ID = B.ID LEFT JOIN T_INFORMATION_STATUS AS C ON A.STATUS_ID = C.ID WHERE 1 = 1 AND A.IS_DELETE = 0 AND A.CREATED_BY = #{createdBy} AND A.CREATED_BY_ENTERPRISE = #{enterpriseId} <if test="typeId != null"> AND A.TYPE_ID = #{typeId} </if> <if test="title != null and title != ''"> AND A.TITLE LIKE CONCAT('%',#{title},'%') </if> <if test="classifyId != null"> AND A.CLASSIFY_ID = #{classifyId} </if> <if test="statusId != null"> AND A.STATUS_ID = #{statusId} </if> <if test="enterpriseId != null "> </if> <if test="startTime != null and endTime != null"> AND DATE(A.CREATED_TIME) BETWEEN #{startTime} AND #{endTime} </if> ORDER BY A.IS_TOP DESC,A.CREATED_TIME DESC 优化这串sql
时间: 2024-02-14 08:04:13 浏览: 114
好的,以下是我对这个SQL查询语句的优化建议:
1. 将 WHERE 子句中的常量条件放在 AND 后面,以便使用索引。例如,将 `1=1` 改为 `A.IS_DELETE = 0`。
2. 对于可选条件,可以使用动态SQL的方式来生成查询语句,以避免无效的条件造成的性能影响。例如,对于 typeId、title、classifyId 和 statusId 这些可选条件,可以使用 `<if>` 标签来判断是否需要在 WHERE 子句中添加对应的条件。
3. 对于多表关联查询,最好使用 INNER JOIN 或者 WHERE EXISTS 来代替 LEFT JOIN,因为 INNER JOIN 或者 WHERE EXISTS 更能利用索引加速查询,并且可以避免不必要的关联查询。
4. 对于 ORDER BY 子句中的多个排序条件,最好将 IS_TOP 和 CREATED_TIME 分别作为两个 ORDER BY 子句,以避免排序操作过于复杂。
优化后的SQL查询语句如下所示:
```
SELECT
A.ID,
A.TITLE,
A.CLASSIFY_ID,
B.CLASSIFY_NAME,
A.CREATED_BY_ENTERPRISE_NAME,
A.CREATED_BY_NAME,
A.CREATED_TIME,
A.SHOW_STATUS_ID,
A.SHOW_STATUS,
A.STATUS_ID,
C.STATUS,
A.IS_TOP
FROM
T_INFORMATION_INFO AS A
INNER JOIN T_INFORMATION_CLASSIFY AS B ON A.CLASSIFY_ID = B.ID
INNER JOIN T_INFORMATION_STATUS AS C ON A.STATUS_ID = C.ID
WHERE
A.IS_DELETE = 0
AND A.CREATED_BY = #{createdBy}
<if test="enterpriseId != null">
AND A.CREATED_BY_ENTERPRISE = #{enterpriseId}
</if>
<if test="typeId != null">
AND A.TYPE_ID = #{typeId}
</if>
<if test="title != null and title != ''">
AND A.TITLE LIKE CONCAT('%',#{title},'%')
</if>
<if test="classifyId != null">
AND A.CLASSIFY_ID = #{classifyId}
</if>
<if test="statusId != null">
AND A.STATUS_ID = #{statusId}
</if>
<if test="startTime != null and endTime != null">
AND DATE(A.CREATED_TIME) BETWEEN #{startTime} AND #{endTime}
</if>
ORDER BY
A.IS_TOP DESC,
A.CREATED_TIME DESC;
```
希望这些优化建议能够帮助您优化这个SQL查询语句。
阅读全文