且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MYSQL:如何加快 sql 查询以获取数据

更新时间:2022-11-26 18:25:44

作为初学者:我根本没有看到子查询的意义.据推测,您的查询可以直接在 where 子句中进行过滤:

As a starter: I don't see the point for the subquery at all. Presumably, your query could filter directly in the where clause:

select id, symbolid_id, volume, close
from daily_price_history
where datetime >= 1598471533546 and symbolname in ('A', 'AA', ...)

然后,您需要 (datetime, symbolname) 的索引:

Then, you want an index on (datetime, symbolname):

create index idx_daily_price_history 
    on daily_price_history(datetime, symbolname)
;

索引的第一列与 datetime 上的谓词匹配.然而,不太可能的是,数据库将能够使用索引根据大量值过滤symbolname.

The first column of the index matches on the predicate on datetime. It is not very likley, however, that the database will be able to use the index to filter symbolname against a large list of values.

另一种方法是将值列表放入表格中,例如 symbolnames.

An alternative would be to put the list of values in a table, say symbolnames.

create table symbolnames (
    symbolname varchar(50) primary key
);
insert into symbolnames values ('A'), ('AA'), ...; 

然后你可以这样做:

select p.id, p.symbolid_id, p.volume, p.close
from daily_price_history p
inner join symbolnames s on s.symbolname = p.symbolname
where s.datetime >= 1598471533546

这应该允许数据库使用上述索引.我们可以向前迈出一步,尝试将 select 子句的 4 列添加到索引中:

That should allow the database to use the above index. We can take one step forward and try and add the 4 columns of the select clause to the index:

create index idx_daily_price_history_2 
    on daily_price_history(datetime, symbolname, id, symbolid_id, volume, close)
;