我正在做一些相當大的一組數據,並試圖從四個不同的數據組合的每個組合創建一個查詢。所有這些組合形成了驚人的1.22億行。然後,我試圖找到一個小於一定數量的權重,並按照從最高到最低的另一個值進行排序。MySQL查詢與小於和ORDER BY DESC
我可以使用weight < x
沒問題。
我可以使用weight < x order by height ASC
沒問題。
當x位於上下兩端時,我甚至可以使用weight < x order by height DESC
。但是一旦它開始蔓延到中間,它就會很快從幾秒鐘上升到幾分鐘,直到「我不會等那麼久。」
有什麼想法? (該名稱已經更改,但種類卻沒有)
的創建:
CREATE TABLE combinations (
id bigint(20) unsigned NOT NULL auto_increment,
up smallint(2) NOT NULL,
left smallint(2) NOT NULL,
right smallint(2) NOT NULL,
down smallint(2) NOT NULL,
weight decimal(5,1) NOT NULL,
width smallint(3) NOT NULL,
forward decimal(6,2) NOT NULL,
backwards decimal(5,2) NOT NULL,
in decimal(7,2) NOT NULL,
out smallint(3) NOT NULL,
height smallint(3) NOT NULL,
diameter decimal(7,2) NOT NULL,
PRIMARY KEY (id)
);
指數
ALTER TABLE combinations ADD INDEX weight_and_height(weight,height);
查詢
SELECT * FROM combinations WHERE weight < 20 ORDER BY height DESC limit 0,5;
的解釋
| id | select type | table | type | possible_keys | key | key_len | ref | rows | extra |
| 1 | simple | combinations | index | weight_and_height | weight_and_height | 5 | NULL | 10 | using where |
我認爲查詢計劃會自動做到這一點?首先通過
johnrom
看看'EXPLAINs'。您可能會發現有些使用索引,有些則不使用。優化器無法準確地做出兩者之間的決定。我懷疑你正在看到一個它做出錯誤選擇的案例。 –
2個範圍(重量和高度)不能同時使用。想象一下按字母順序排列的人員列表 - 按姓氏和名字排序。現在假設你想找到所有擁有我的姓名縮寫的人(J.,R.)。'INDEX(last,first)'沒有用,它只是簡單地掃描所有'last LIKE'J%''檢查每個一個用於'R'。你需要一個2D索引。我看到的最接近的是[緯度/經度搜索](http://mysql.rjweb.org/doc.php/latlng),它可能適用於您的應用程序。 –