【发布时间】:2019-01-22 14:18:50
【问题描述】:
我有以下要优化的 SQL 查询:
select table1.tiers as col1, table1.id_item as col2
from items table1
where (table1.tiers is not null)
and table1.tiers<>''
and table1.id_item = (select max(table2.id_item)
from items table2
where table1.tiers=table2.tiers)
and table1.n_version_item=(select max(table2.n_version_item)
from items table2
where table2.id_item=table1.id_item)
我试过这个:
select table1.tiers as col1, table1.id_item as col2
from items table1
where (table1.tiers is not null)
and table1.tiers<> ''
and CONCAT(table1.id_item,table1.n_version_item) = (select CONCAT(max(table2.id_item),max(table2.n_version_item))
from items table2
where table2.id_item=table1.id_item
and table1.tiers=table2.tiers)
但我没有得到相同的结果。原始的第一个查询返回的行数少于修改后的行数。请注意,表项有一个主键(id、version),并且对于每一对,都会影响一个层。
【问题讨论】:
-
不要在查询中重复使用同一个表别名 (table1)。
-
where (id_item, n_version_item) = (select max(t2.id_item), max(t2.n_version_item) from ...) -
我知道 SQL 只是一种查询语言。第一个查询是由休眠生成的。而且我在日志文件中注意到它需要太长时间。这就是为什么我想以另一种方式重写它以解决性能问题谢谢
-
我正在使用 MySQL
-
@user3474488 它的一些数据不应该导致性能问题。您可以创建索引,因为在您的查询中您没有使用 PK
标签: mysql sql query-performance