I have two tables, and now I must order table's A by B 's count:
A:
id | name | status
--- |-----------|---------
1 | test | 1
2 | this is 2| 1
B:
id | a_id | user_id
---|------|----------
1 | 1 | 12
2 | 1 | 13
3 | 1 | 14
4 | 2 | 12
5 | 2 | 15
Now I want to fetch limit 5 of the most users from table A :
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
I have created index for a_id
column in table B .
After executed, explain :
*************************** 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)
I find that the first used Using temporary; Using filesort , I know this must be refactored!
But how can I do it?
Why do you need subquery?
Won't this work for you:
SELECT a.name, COUNT(b.id) as total
FROM tb_a a
INNER JOIN tb_b b ON a.id = b.a_id
WHERE a.status = 1
GROUP BY a.id
ORDER BY COUNT(b.id) DESC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.