如何使MySQL查询更快

时间:2019-04-15 12:54:07

标签: mysql performance

由@RolandStarke先生解决

将DATE(t4。date)更改为t4。date,它将使用索引

  

查询花费了0.5519秒。


我正在尝试使此查询更加快速

没有连接的第一个查询

SELECT `productTitle`,`orderCnt`,`promPCPriceStr`,`productImgUrl`,`oriPriceStr`,`detailUrl`,
(
select count(id) from orders t4 WHERE
 t4.productId = t1.productId 
and DATE( t4.`date`) > DATE_SUB(CURDATE(), INTERVAL 2 DAY) 
) as ordertoday 

FROM `products` t1 
WHERE `orderCnt` > 0 
AND `orderCnt` < 2000 
AND `promPCPriceStr` > 0 
AND `promPCPriceStr` < 2000 
HAVING ordertoday > 5 AND ordertoday < 2000 
order by ordertoday desc limit 150

结果是

  

查询耗时4.0222秒。

说明结果

1

带有联接的第二个查询#

SELECT  `productTitle`,`orderCnt`,`promPCPriceStr`,`productImgUrl`,`oriPriceStr`,`detailUrl` FROM `products` p 
INNER JOIN
(
select count(id) AS filterd_orders,productId from orders t4 WHERE DATE( t4.`date`) > DATE_SUB(CURDATE(), INTERVAL 2 DAY)  
GROUP by productId
) o

ON p.productID = o.productId

AND `orderCnt` > 0 AND `orderCnt` < 2000 AND `promPCPriceStr` > 0 AND `promPCPriceStr` < 2000 
and filterd_orders > 5 
AND filterd_orders < 2000 
order by filterd_orders desc limit 30
  

查询耗时4.8217秒。

说明结果

1

子查询结果

select count(id) AS filterd_orders,productId from orders t4 WHERE DATE( t4.`date`) > DATE_SUB(CURDATE(), INTERVAL 3 DAY) GROUP by productId
  

查询耗时0.0044秒。

说明结果

1

表结构

产品表

CREATE TABLE `products` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `productId` bigint(20) NOT NULL,
 `detailUrl` text CHARACTER SET utf32 NOT NULL,
 `belongToDSStore` int(11) NOT NULL,
 `promPCPriceStr` float NOT NULL DEFAULT '-1',
 `oriPriceStr` float NOT NULL DEFAULT '-1',
 `orderCnt` int(11) NOT NULL,
 `productTitle` text CHARACTER SET utf32 NOT NULL,
 `productImgUrl` text CHARACTER SET utf32 NOT NULL,
 `created_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `cat` bigint(20) NOT NULL DEFAULT '-1',
 PRIMARY KEY (`id`),
 UNIQUE KEY `productId` (`productId`),
 KEY `orderCnt` (`orderCnt`),
 KEY `cat` (`cat`),
 KEY `promPCPriceStr` (`promPCPriceStr`)
) ENGINE=InnoDB AUTO_INCREMENT=37773 DEFAULT CHARSET=latin1

订单表

CREATE TABLE `orders` (
 `oid` int(11) NOT NULL AUTO_INCREMENT,
 `countryCode` varchar(10) NOT NULL,
 `date` datetime NOT NULL,
 `id` bigint(20) NOT NULL,
 `productId` bigint(20) NOT NULL,
 PRIMARY KEY (`oid`),
 UNIQUE KEY `id` (`id`),
 KEY `date` (`date`),
 KEY `productId` (`productId`)
) ENGINE=InnoDB AUTO_INCREMENT=9790205 DEFAULT CHARSET=latin1

  

innodb_buffer_pool_size =   {DBInstanceClassMemory * 3/4}

服务器硬件

  • AWS RDS db.t2.medium
  • 4 GB RAM
  • 2个CPU内核2.5Hz

0 个答案:

没有答案