简体   繁体   English

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

[英]Optimize SQL-query in big database?

Query 询问

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

MySQL returns: MySQL返回:

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

if i remove ORDER BY id DESC 如果我删除ID DESC的ORDER BY

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

Explain plan: 说明计划:

count 计数

SELECT count( * )
FROM user_ip_tmp

在此处输入图片说明

Example of the database used 使用的数据库示例

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 ;

I want the correct way to do the query and optimize database for ORDER BY id DESC 我想要正确的方法来查询和优化数据库以ORDER BY id DESC

It would be interesting to know something about the distribution of your data. 知道一些有关数据分布的信息将很有趣。 Could you add the results of the following queries to your post? 您能否将以下查询的结果添加到您的帖子中? (no need for pictures, plain text will do). (无需图片,纯文本即可)。

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/'; 

Also, could you test this alternative for performance? 另外,您可以测试这种替代方法的性能吗? EDIT: alias for subquery 编辑:子查询的别名

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

Edit If it is an option to add and experiment with indexes, then you could try one of these (or both and see which is better) 编辑如果可以选择添加索引并尝试使用索引,则可以尝试使用其中一个(或同时尝试两个,看看哪个更好)

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

您可以使用以下方法创建索引:

 id, too and contry

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM