获取最新数据 - 优化SQL查询

时间:2016-07-31 21:54:08

标签: mysql query-optimization

我正在使用以下SQL查询以从数据库中获取最新数据。

SELECT d.id AS id_d,
       d.id_user AS id_du,
       d.id_channel AS id_dc,
       d.datetime_logged AS logged

FROM discord AS d
JOIN discord_users AS du
ON d.id_user = du.id
WHERE datetime_logged IN (SELECT MAX(datetime_logged) FROM discord)
ORDER BY du.data_name ASC

以下是数据库的样子:

CREATE TABLE IF NOT EXISTS `discord` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_user` int(11) NOT NULL,
  `id_channel` varchar(50) NOT NULL,
  `id_game` int(11) NOT NULL,
  `data_muted_server` tinyint(4) NOT NULL,
  `data_muted_self` tinyint(4) NOT NULL,
  `data_deafen_server` tinyint(4) NOT NULL,
  `data_deafen_self` tinyint(4) NOT NULL,
  `data_suppressed` tinyint(4) NOT NULL,
  `data_status` varchar(10) NOT NULL,
  `data_game` text,
  `datetime_logged` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
)

CREATE TABLE IF NOT EXISTS `discord_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data_id` text NOT NULL,
  `data_name` varchar(50) NOT NULL,
  `data_avatar` text,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
)

该查询需要"年龄"载入。但是,如果我删除WHERE datetime_logged IN (SELECT MAX(datetime_logged) FROM discord)并将LIMIT 10添加到查询中,则页面加载速度超快!

SQL查询的目的是仅获取表discord中的最新数据。由于数据每15分钟只会更新一次,因此查询将轻松获取最新数据。

discorddiscord_users的关系是discord需要来自discord_users的ID才能从用户那里获取信息。

进一步回答symcbean的问题:

Q)为什么,当您根据"很多"的内容将输出限制为单个记录时。关系的一面,你是按照"一个"侧?

A)你是什么意思?

Q)为什么在桌面上没有差异索引的情况下在discord_users表上打开2个游标?

A)再一次,你的意思是什么? :)

所以这是我的问题。如何优化我的SQL查询,以便加载页面需要将近1分钟?这是指向该页面的链接:https://erik-edgren.nu/discord

1 个答案:

答案 0 :(得分:0)

如果您仍有问题,请尝试此选项。在INDEX表的index_datelog列上创建datetime_logged例如discord。然后尝试以下查询

SELECT 
    d.id AS id_d, d.id_user AS id_du, d.id_channel AS id_dc, d.datetime_logged AS logged 
FROM 
    discord d 
JOIN 
    discord_users du ON d.id_user = du.id USE INDEX(index_datelog))
WHERE 
    d. datetime_logged = (SELECT MAX(datetime_logged) FROM discord)
ORDER BY d.datetime_logged ASC