无论如何都要优化以下查询:
SELECT
t1.id,
(SELECT SUM(col1) FROM table_name_two t2 WHERE t2.name LIKE CONCAT('%',t1.name)) AS col1_count
FROM
table_name_one t1
ORDER BY
col1_count DESC
使用ORDER BY col1_count DESC
需要很长时间。
感谢。
答案 0 :(得分:2)
只需在连接的on
子句中进行正常连接:
SELECT
t1.id,
SUM(t2.col1) AS col1_count
FROM table_name_one t1
LEFT JOIN table_name_two t2 on t2.name LIKE CONCAT('%', t1.name)
GROUP BY 1
ORDER BY 2 DESC
它应该以这种方式方式 - 它基本上是一个查询而不是“n”查询,尽管它不会从使用LIKE
运算符的索引获得任何帮助%