1
的這個SQL我有兩個表,現在我必須訂購表的一個通過乙的計數:如何提高性能的MySQL
答:
id | name | status
--- |-----------|---------
1 | test | 1
2 | this is 2| 1
乙:
id | a_id | user_id
---|------|----------
1 | 1 | 12
2 | 1 | 13
3 | 1 | 14
4 | 2 | 12
5 | 2 | 15
現在我wa在表乙
SELECT a.name, b.total
FROM tb_a a
INNER JOIN (SELECT COUNT(*) total, a_id FROM tb_b GROUP BY a_id) b
ON a.id = b.a_id
WHERE a.status = 1
ORDER BY b.`total` DESC
我已經創建索引a_id
柱:NT抓取限制大多數用戶的5從表甲。
執行後,解釋:
*************************** 1. row ***************************
id: 1
select_type: PRIMARY
table: a
type: ALL
possible_keys: PRIMARY
key: NULL
key_len: NULL
ref: NULL
rows: 2
Extra: Using where; Using temporary; Using filesort
*************************** 2. row ***************************
id: 1
select_type: PRIMARY
table: <derived2>
type: ref
possible_keys: <auto_key0>
key: <auto_key0>
key_len: 4
ref: test.a.id
rows: 2
Extra: NULL
*************************** 3. row ***************************
id: 2
select_type: DERIVED
table: tb_b
type: index
possible_keys: idx_id
key: idx_id
key_len: 4
ref: NULL
rows: 7
Extra: Using index
3 rows in set (0.00 sec)
我發現,先用使用臨時;使用filesort,我知道這必須重構!
但我該怎麼辦?
它的工作原理!解釋之後: ''' – light
@light:很高興聽到:)然後將問題標記爲回答:) – cyadvert
但我想知道使用這種方式的好處。因爲現在也有'臨時使用;使用filesort'。不像我的SQL,解釋後只有兩個結果.. – light