我有以下(简化的)Mysql 表:
Requests:
+----------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------------+--------------+------+-----+---------+-------+
| ID | bigint(20) | NO | PRI | NULL | |
| UniqueIdentifier | varchar(255) | YES | MUL | NULL | |
| UniversalServiceId | bigint(20) | YES | MUL | NULL | |
+----------------------+--------------+------+-----+---------+-------+
观察结果:
+---------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+--------------+------+-----+---------+-------+
| ID | bigint(20) | NO | PRI | NULL | |
| Value | varchar(255) | NO | | NULL | |
| RequestId | bigint(20) | NO | MUL | NULL | |
+---------------------+--------------+------+-----+---------+-------+
我已对 UniqueIdentifier、UniversalServiceId 和 RequestId 建立了索引。
使用 RequestId 上的 JOIN 来根据 UniqueIdentifier 和 UniversalServiceId 查询表。
观察表有数百万条记录。查询返回的速度非常慢,我想知道是否可以采取任何措施来提高性能。我刚刚开始阅读有关 memcache 的内容,但似乎只有在对特定数据集进行第一次查询(通常是唯一一次查询)之后它才可能有用。
这是正在使用的查询类型:
select * from Observations where RequestId in (select ID from Requests where UniqueIdentifier = '123456' and UniversalServiceId = '1234'
任何建议/指导表示赞赏!
最佳答案
我建议您使用包含 JOIN 操作的查询,而不是 IN(子查询)
谓词。
例如:
SELECT o.ID
, o.Value
, o.RequestId
FROM Observations o
JOIN Requests r
ON r.ID = o.RequestId
WHERE r.UniqueIdentifier = '123456'
AND r.UniversalServiceId = '1234'
为了获得最佳性能,合适的索引是:
... ON Requests (UniversalServiceId, UniqueIdentifier, ID)
... ON Observations (RequestId, Value, ID)
(请求表索引中前导列的选择取决于预期的基数。)
关于MySQL 性能和 Memcache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27053258/