嗨,我有一个mysql查询,它将以最大状态计数返回post_id,它当前显示的结果是
POST_ID
3
Mysql表:
(`post_id`, `user_id`, `status`, `date_created`)
(2, 2, 'funny', 20121022120627)
(2, 3, 'lame', 20121023120627)
(3, 1, 'useful', 20121023120627)
(3, 3, 'lame', 20121023120627)
(3, 4, 'useful', 20121023120627)
(4, 4, 'useful', 20121024120627)
但我需要的结果是,在desc order.if 2结果具有相同数字时显示从max到min的计数,那么最高结果将基于最新的date_created类似这样
POST_ID
3
2
4
我当前的查询是
SELECT post_id
FROM tableName
GROUP BY post_ID
HAVING COUNT(*) =
(
SELECT MAX(x.counts)
FROM
(
SELECT post_id, COUNT(*) counts
FROM tableName
GROUP BY post_id
) x
)
可以在SQLFiddle SQLFiddle
上找到该示例答案 0 :(得分:5)
但我需要的结果是,在desc上显示从max到min的计数 order.if 2结果具有相同的数字,那么最高的结果将是 基于最新的date_created。
您需要ORDER BY COUNT(*) DESC, date_created DESC
这样:
SELECT post_id
FROM tableName
GROUP BY post_ID
HAVING COUNT(*) =
(
SELECT MAX(x.counts)
FROM
(
SELECT post_id, COUNT(*) counts
FROM tableName
GROUP BY post_id
) x
)
ORDER BY COUNT(*) DESC, date_created DESC
更新1
试试这个,
SELECT post_id
FROM tableName
GROUP BY post_ID
ORDER BY COUNT(*) DESC, MAX(`date_created`) DESC