1. 程式人生 > 資料庫 >2020-12-26:mysql中,表person有欄位id、name、age、sex,id是主鍵,name是普通索引,age和sex沒有索引。select * from person where i

2020-12-26:mysql中,表person有欄位id、name、age、sex,id是主鍵,name是普通索引,age和sex沒有索引。select * from person where i

2020-12-26:mysql中,表person有欄位id、name、age、sex,id是主鍵,name是普通索引,age和sex沒有索引。select * from person where id=1 and name='james' and age=1 and sex=0。請問這條語句有幾次回表?

福哥答案2020-12-26:

答案是沒有回表。

一般題目是判斷有沒有回表,而這道題是要說出有幾次回表。

剛開始以為會用到回表。後來想了想,沒有回表。id是等值查詢,頂多命中1條資料。然後再對這1條資料做name過濾,就這麼1條資料,沒必要回表查詢,連我都能想到,mysql的作者更能想到,mysql沒那麼傻。

有什麼不對的地方,請直接留言評論。

1.建立表和插入資料:
-- ----------------------------
-- Table structure for `person` 表結構
-- ----------------------------
DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`age` int(11) NOT NULL,
`sex` tinyint(4) NOT NULL,
PRIMARY KEY (`id`),

KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of person,表中記錄
-- ----------------------------
INSERT INTO `person` VALUES ('1', 'james', '11', '1');
INSERT INTO `person` VALUES ('2', 'haha', '12', '0');
INSERT INTO `person` VALUES ('3', '福大大', '13', '2');

2.檢視執行計劃:
EXPLAIN SELECT * FROM person WHERE id=3;
EXPLAIN SELECT * FROM person WHERE id=3 AND name='福大大';
EXPLAIN SELECT * FROM person WHERE id=3 AND name='福大大' AND age=13;
EXPLAIN SELECT * FROM person WHERE id=3 AND name='福大大' AND age=13 AND sex=2;

 

 


***
[評論](https://user.qzone.qq.com/3182319461/blog/1608939505)