似乎您还需要一个聚合体。在您的价值上使用MAX()
聚合和:cnt
GROUP BY placeId, userVotedId
SELECT placeId, userVotedId, max(cnt)
FROM
(
SELECT uvo.userVotedId, p.placeId, count(*) as cnt
FROM users as u
INNER JOIN users_votes as uvo
ON u.userId = uvo.userVotedId
INNER JOIN places as p
ON p.placeId = uvo.placeId
GROUP BY userVotedId, placeId
) AS RESULT
GROUP BY placeId, userVotedId
注意:我将您的查询更改为使用JOIN
语法而不是表之间的逗号。
编辑,根据您的评论,以下应该有效:
select total.uservotedid,
total.placeid,
total.cnt
from
(
SELECT uvo.userVotedId, p.placeId, count(*) as cnt
FROM users as u
INNER JOIN users_votes as uvo
ON u.userId = uvo.userVotedId
INNER JOIN places as p
ON p.placeId = uvo.placeId
GROUP BY userVotedId, placeId
) total
inner join
(
select max(cnt) Mx, placeid
from
(
SELECT uvo.userVotedId, p.placeId, count(*) as cnt
FROM users as u
INNER JOIN users_votes as uvo
ON u.userId = uvo.userVotedId
INNER JOIN places as p
ON p.placeId = uvo.placeId
GROUP BY userVotedId, placeId
) mx
group by placeid
) src
on total.placeid = src.placeid
and total.cnt = src.mx
请参阅带有演示的 SQL Fiddle
结果是:
| USERVOTEDID | PLACEID | CNT |
-------------------------------
| 65 | 11 | 1 |
| 67 | 13 | 1 |
| 67 | 25 | 1 |
| 67 | 51 | 2 |
编辑#2,如果你想在平局时返回一个随机数,那么你可以使用用户变量:
select uservotedid,
placeid,
cnt
from
(
select total.uservotedid,
total.placeid,
total.cnt,
@rownum := case when @prev = total.placeid then @rownum+1 else 1 end rownum,
@prev := total.placeid pplaceid
from
(
SELECT uvo.userVotedId, p.placeId, count(*) as cnt
FROM users as u
INNER JOIN users_votes as uvo
ON u.userId = uvo.userVotedId
INNER JOIN places as p
ON p.placeId = uvo.placeId
GROUP BY userVotedId, placeId
) total
inner join
(
select max(cnt) Mx, placeid
from
(
SELECT uvo.userVotedId, p.placeId, count(*) as cnt
FROM users as u
INNER JOIN users_votes as uvo
ON u.userId = uvo.userVotedId
INNER JOIN places as p
ON p.placeId = uvo.placeId
GROUP BY userVotedId, placeId
) mx
group by placeid
) src
on total.placeid = src.placeid
and total.cnt = src.mx
order by total.placeid, total.uservotedid
) src
where rownum = 1
order by placeid, uservotedid
请参阅带有演示的 SQL Fiddle