gpt4 book ai didi

mysql - 在大数据库中优化 SQL 查询?

转载 作者:可可西里 更新时间:2023-11-01 07:37:54 25 4
gpt4 key购买 nike

查询

SELECT *
FROM user_ip_tmp
WHERE too = 'http://example.com/'
AND contry != 'CN'
AND contry != 'TW'
ORDER BY id DESC
LIMIT 50

MySQL 返回:

Showing rows 0 - 29 ( 50 total, Query took 11.9276 sec) [id: 3452538 - 3448824]

如果我删除 ORDER BY id DESC

Showing rows 0 - 29 ( 50 total, Query took 0.0033 sec)

解释计划:

计数

SELECT count( * )
FROM user_ip_tmp

enter image description here

使用的数据库示例

CREATE TABLE IF NOT EXISTS `user_ip_tmp` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`ip` varchar(20) NOT NULL,
`dataip` bigint(20) NOT NULL,
`ref` text NOT NULL,
`click` int(20) NOT NULL,
`code` varchar(17) NOT NULL,
`too` text NOT NULL,
`checkopen` varchar(17) NOT NULL,
`contry` text NOT NULL,
`vOperation` text NOT NULL,
`vBrowser` text NOT NULL,
`iconOperation` text NOT NULL,
`iconBrowser` text NOT NULL,
PRIMARY KEY (`id`),
KEY `ip` (`dataip`),
KEY `ip` (`checkopen`),
KEY `ip` (`code`),
KEY `ip` (`too`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5426268 ;

我想要正确的方法来为 ORDER BY id DESC 查询和优化数据库

最佳答案

了解有关数据分布的一些信息会很有趣。您能否将以下查询的结果添加到您的帖子中? (不需要图片,纯文本即可)。

SELECT count(*) FROM user_ip_tmp WHERE too = 'http://example.com/' AND contry != 'CN' AND contry != 'TW'; 

SELECT count(*) FROM user_ip_tmp WHERE too = 'http://example.com/';

此外,您能否测试此替代方案的性能? 编辑:子查询的别名

SELECT sub.* FROM
(SELECT *
FROM user_ip_tmp
WHERE too = 'http://example.com/'
AND contry != 'CN'
AND contry != 'TW'
) sub
ORDER BY sub.id DESC
LIMIT 50

编辑 如果添加和试验索引是一个选项,那么您可以尝试其中之一(或同时尝试两者,看看哪个更好)

CREATE INDEX index_name ON `user_ip_tmp` (`too`, `id`);
CREATE INDEX index_name ON `user_ip_tmp` (`too`, `contry`, `id`);

关于mysql - 在大数据库中优化 SQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8120673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com