PERBARUI:
Lanjut ke komentar baru di bawah ini:
(
SELECT t.*, COUNT(*) AS tagcount
FROM tagged td
LEFT JOIN tags t ON (t.id = td.tag_id)
GROUP BY td.tag_id
ORDER BY tagcount DESC, t.title ASC
LIMIT 3
) ORDER BY title ASC;
Hasil:
+------+------------+----------+
| id | title | tagcount |
+------+------------+----------+
| 3 | javascript | 2 |
| 1 | mysql | 2 |
| 2 | php | 3 |
+------+------------+----------+
3 rows in set (0.00 sec)
Cukup ubah LIMIT 3
ke LIMIT 10
untuk mendapatkan 10 besar alih-alih 3 teratas.
Jawaban Sebelumnya:
Mengapa Anda tidak menambahkan LIMIT 10
untuk pertanyaan Anda?
SELECT t.*, COUNT(*) AS tagcount
FROM tagged td
LEFT JOIN tags t ON (t.id = td.tag_id)
GROUP BY td.tag_id
ORDER BY tagcount DESC, t.title ASC
LIMIT 10;
Kasus uji:
CREATE TABLE tags (id int, title varchar(20));
CREATE TABLE tagged (tag_id int, post_id int);
INSERT INTO tags VALUES (1, 'mysql');
INSERT INTO tags VALUES (2, 'php');
INSERT INTO tags VALUES (3, 'javascript');
INSERT INTO tags VALUES (4, 'c');
INSERT INTO tagged VALUES (1, 1);
INSERT INTO tagged VALUES (2, 1);
INSERT INTO tagged VALUES (1, 2);
INSERT INTO tagged VALUES (2, 2);
INSERT INTO tagged VALUES (3, 3);
INSERT INTO tagged VALUES (2, 4);
INSERT INTO tagged VALUES (3, 4);
INSERT INTO tagged VALUES (4, 5);
Hasil (menggunakan LIMIT 3
):
+------+------------+----------+
| id | title | tagcount |
+------+------------+----------+
| 2 | php | 3 |
| 3 | javascript | 2 |
| 1 | mysql | 2 |
+------+------------+----------+
3 rows in set (0.00 sec)
Perhatikan bagaimana [c]
tag keluar dari 3 hasil teratas, dan baris diurutkan menurut abjad jika seri.