我确定了我的疑问:
SELECT *
FROM `participation`
LEFT JOIN parties ON parties.id = participation.party_id
WHERE `riding_id` = 10001
AND `election_id` = 41
ORDER BY num_votes DESC
LIMIT 1
这准确地产生了我想要的结果。
结果是投票最多的一方。
现在我想在TABLE ridings 的每一行上执行相同的查询
其中包含所有riding_id
行。遇到麻烦了。
我不想加入另一个表 - 但是要遍历每一行并执行与上面相同的计算 - 每行。
类似的东西:
SELECT *
FROM `participation`
LEFT JOIN parties ON parties.id = participation.party_id
WHERE `riding_id` = "LOOP ALL riding_id IN ridings TABLE"
AND `election_id` = 41
ORDER BY num_votes DESC
LIMIT 1
任何帮助都将不胜感激。
答案 0 :(得分:1)
使用子查询很有吸引力:
SELECT *
FROM participation LEFT JOIN
parties
ON parties.id = participation.party_id
WHERE riding_id IN (SELECT riding_id FROM ridings) AND
election_id = 41
ORDER BY num_votes DESC
但是,你不再获得最高票数。你得到了一切。
以下是使用变量获取每个riding_id
的最高投票数的方法:
SELECT *
FROM (SELECT *,
(@rn := if(@r = riding_id, @rn + 1,
if(@rn := riding_id, 1, 1)
)
) as seqnum
FROM participation LEFT JOIN
parties
ON parties.id = participation.party_id CROSS JOIN
(SELECT @rn := 0, @r := -1) params
WHERE riding_id IN (SELECT riding_id FROM ridings) AND
election_id = 41
ORDER BY riding_id, num_votes DESC
) pp
WHERE seqnum = 1;