我有以下查询按预期工作。
SELECT T.*, @curRank := @curRank + 1 AS rank
FROM ( SELECT e.guid,
e.name,
(SELECT COUNT(ev.event_vote_id)
FROM event_vote ev
WHERE ev.event_uid = s.guid) AS votes
FROM event e
) as T
CROSS JOIN (SELECT @curRank := 0) r
ORDER BY votes DESC
它返回所有事件的guid,名称,投票数和排名。
但是我想通过使用以下内容链接 user_event 表来使其特定于某个用户:
JOIN user_event ON t.guid = ue.event_uid
WHERE ue.user_uid = 'abc123'
但是,我不确定将此放在哪里或是否这样。
我将以下查询作为开头,但它返回与预期相反的情况,即每个不属于该用户的事件。
SELECT t.*
FROM user_event ue
JOIN ( SELECT e.guid,
e.name,
e.ownerId,
e.thumbnailSrc,
@curRank := @curRank + 1 AS rank,
( SELECT COUNT(ev.event_vote_id)
FROM event_vote ev
WHERE ev.event_uid = e.guid) AS votes
FROM event e, (SELECT @curRank := 0) r
) AS t
ON t.guid = ue.event_uid
WHERE ue.user_uid = 'abc123'
ORDER BY rank ASC
预期结果
所有活动的清单:
guid | name | votes | rank
def test2 2 1 (user1)
abc test1 1 2 (user2)
ghi test3 0 3 (user1)
jkl test4 0 4 (user3)
查询应返回给用户1的内容(user1 guid为abc123)
guid | name | votes | rank
def test2 2 1
ghi test3 0 3
答案 0 :(得分:1)
如果您只想要来自某个特定用户的活动,请暂时忘记排名:
SELECT e.*, ue.*, ( ... ) as votes
FROM event e
JOIN user_event ue
ON e.guid = ue.event_uid
WHERE ue.user_uid = 'abc123'
在结果上你可以做排名。
SELECT T.*, @curRank := @curRank + 1 AS rank
FROM ( ... previous query ... ) as T
CROSS JOIN (SELECT @curRank := 0) r
ORDER BY votes DESC
修改强>
过滤您需要的单个用户创建另一个子查询。
所以查询变为:
SELECT *
FROM ( SELECT T.*, @curRank := @curRank + 1 AS rank
FROM ( SELECT e.*, ue.*, ( ... ) as votes
FROM event e
JOIN user_event ue
ON e.guid = ue.event_uid ) as T
CROSS JOIN (SELECT @curRank := 0) r
ORDER BY votes DESC
) as ranked_result
WHERE ranked_result.user_uid = 'abc123'