首页 > 数据库 > 数据库开发技术 > MySQL面试题:一个优化案例
CREATE TABLE `customer` (
`C_CUSTKEY` int NOT NULL,
`C_NAME` varchar(25) NOT NULL,
`C_ADDRESS` varchar(40) NOT NULL,
`C_NATIONKEY` int NOT NULL,
`C_PHONE` char(15) NOT NULL,
`C_ACCTBAL` decimal(15,2) NOT NULL,
`C_MKTSEGMENT` char(10) NOT NULL,
`C_COMMENT` varchar(117) NOT NULL,
PRIMARY KEY (`C_CUSTKEY`)
) ENGINE=InnoDB;
-- tpch.orders definition
CREATE TABLE `orders` (
`O_ORDERKEY` int NOT NULL,
`O_CUSTKEY` int NOT NULL,
`O_ORDERSTATUS` char(1) NOT NULL,
`O_TOTALPRICE` decimal(15,2) NOT NULL,
`O_ORDERDATE` date NOT NULL,
`O_ORDERPRIORITY` char(15) NOT NULL,
`O_CLERK` char(15) NOT NULL,
`O_SHIPPRIORITY` int NOT NULL,
`O_COMMENT` varchar(79) NOT NULL,
PRIMARY KEY (`O_ORDERKEY`)
) ENGINE=InnoDB;
select *
from customer
where c_custkey = (select max(o_custkey)
from orders
where subdate(o_orderdate, interval '1' DAY) < '2022-12-20');
EXPLAIN
select * from customer
where c_custkey = (select max(o_custkey)
from orders where subdate(o_orderdate, interval '1' DAY) < '2022-12-20');
id|select_type|table |partitions|type|possible_keys|key|key_len|ref|rows|filtered|Extra |
--+-----------+------+----------+----+-------------+---+-------+---+----+--------+------------------------------+
1|PRIMARY | | | | | | | | | |no matching row in const table|
2|SUBQUERY |orders| |ALL | | | | | 1| 100.0|Using where |
CREATE INDEX idx_orders_date ON orders(o_orderdate);
EXPLAIN
select * from customer
where c_custkey = (select max(o_custkey)
from orders where o_orderdate < adddate('2022-12-20', interval '1' DAY));
id|select_type|table |partitions|type |possible_keys |key |key_len|ref|rows|filtered|Extra |
--+-----------+------+----------+-----+---------------+---------------+-------+---+----+--------+------------------------------+
1|PRIMARY | | | | | | | | | |no matching row in const table|
2|SUBQUERY |orders| |range|idx_orders_date|idx_orders_date|3 | | 1| 100.0|Using index condition |
CREATE INDEX idx_orders_date_cust ON orders(o_orderdate, o_custkey);
EXPLAIN
select * from customer
where c_custkey = (select max(o_custkey)
from orders where o_orderdate < adddate('2022-12-20', interval '1' DAY));
id|select_type|table |partitions|type |possible_keys |key |key_len|ref|rows|filtered|Extra |
--+-----------+------+----------+-----+------------------------------------+--------------------+-------+---+----+--------+------------------------------+
1|PRIMARY | | | | | | | | | |no matching row in const table|
2|SUBQUERY |orders| |index|idx_orders_date,idx_orders_date_cust|idx_orders_date_cust|7 | | 1| 100.0|Using where; Using index |
原文作者:SQL编程思想;如有侵权,请联系管理员删除。