要找出最好的方法是測量它:
沒有索引
隨着指數
結論是:
- 如果您沒有索引,那麼使用哪個查詢並沒有什麼不同。
- 如果您有正確的索引,聯接速度會更快。
- 添加正確索引的效果大於選擇正確查詢的效果。如果性能很重要,請確保您擁有正確的索引。
當然,您的結果可能因MySQL版本和您擁有的數據分佈而異。
以下是我測試過它:
- 百萬學生(25%的狀態1)。
- 50,000門課程。
- 10個部門。
這是我用來創建測試數據的SQL:
CREATE TABLE students
(id INT PRIMARY KEY AUTO_INCREMENT,
status int NOT NULL,
classes_id int NOT NULL);
CREATE TABLE classes
(id INT PRIMARY KEY AUTO_INCREMENT,
departments_id INT NOT NULL);
CREATE TABLE numbers(id INT PRIMARY KEY AUTO_INCREMENT);
INSERT INTO numbers VALUES(),(),(),(),(),(),(),(),(),();
INSERT INTO numbers
SELECT NULL
FROM numbers AS n1
CROSS JOIN numbers AS n2
CROSS JOIN numbers AS n3
CROSS JOIN numbers AS n4
CROSS JOIN numbers AS n5
CROSS JOIN numbers AS n6;
INSERT INTO classes (departments_id)
SELECT id % 10 FROM numbers WHERE id <= 50000;
INSERT INTO students (status, classes_id)
SELECT id % 4 = 0, id % 50000 + 1 FROM numbers WHERE id <= 1000000;
SELECT COUNT(*) AS count
FROM students
WHERE status = 1
AND classes_id IN (SELECT id FROM classes WHERE departments_id = 1);
SELECT COUNT(*) AS count
FROM students s
LEFT JOIN classes c
ON c.id = s.classes_id
WHERE status = 1
AND c.departments_id = 1;
CREATE INDEX ix_students ON students(status, classes_id);
當您測試時哪個速度更快? – symcbean
使用'EXPLAIN'運行並自己查看。例子:'解釋select count(*)...' –
解釋你會得到答案 –