just wondering if it is possible to get the top 10 COUNT results and ordering by COUNT and alphabetically?
I have the following tables,
tags
-------
UPDATE:
Further to the new comment below:
(
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;
Result:
+------+------------+----------+
| id | title | tagcount |
+------+------------+----------+
| 3 | javascript | 2 |
| 1 | mysql | 2 |
| 2 | php | 3 |
+------+------------+----------+
3 rows in set (0.00 sec)
Simply change the LIMIT 3
to LIMIT 10
to get the top 10 instead of the top 3.
Previous Answer:
Why don't you add a LIMIT 10
to your query?
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;
Test case:
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);
Result (using LIMIT 3
):
+------+------------+----------+
| id | title | tagcount |
+------+------------+----------+
| 2 | php | 3 |
| 3 | javascript | 2 |
| 1 | mysql | 2 |
+------+------------+----------+
3 rows in set (0.00 sec)
Note how the [c]
tag fell out of the top 3 results, and rows are ordered alphabetically in case of a tie.
Does the query work? If yes, you could use LIMIT 0, 10
to get only the top 10 rows.
SELECT tag.*, COUNT(td.tag_ID) AS tagcount
FROM Tagged td
LEFT JOIN gen_Tags tag ON td.tag_ID = tag.tag_ID
GROUP BY td.tag_ID
ORDER BY tagcount DESC, tag.tag_Title ASC LIMIT 0, 10
Another thing you might be interested in, is ranking. See here: http://www.fromdual.com/ranking-mysql-results
Edit
Maybe a subquery does what you want:
SELECT list.* FROM (
SELECT tag.*, COUNT(td.tag_ID) AS tagcount,
FROM Tagged td
LEFT JOIN gen_Tags tag ON td.tag_ID = tag.tag_ID
GROUP BY td.tag_ID
ORDER BY tagcount DESC LIMIT 0, 10
) AS list ORDER BY list.tag_Title ASC, list.tagcount DESC