我正在使用此查询:
SELECT `servers`.*, `sponsorships`.`sponsorship_id`, MAX(`sponsorships`.`bid`) as maxbid
FROM `sponsorships`
LEFT JOIN `servers`
ON `sponsorships`.`server_id` = `servers`.`id`
WHERE `sponsorships`.`impressions` <= '1000'
GROUP BY `sponsorships`.`server_id`
ORDER BY maxbid DESC
LIMIT 3;
这给了我以下内容
[1] => Array
(
[id] => 23
[user_id] => 1
[cache_time] => 1395557635
[sponsorship_id] => 1
[maxbid] => 20
)
但是 sponsorship_id => 1
的行不是具有 maxbid 的行。我需要做什么才能从 maxbid 中获取 sponsorship_id
?
更新#1
我有这两个表:
赞助
服务器
我想要这个:
[1] => Array
(
[id] => 23 (servers.id)
[user_id] => 1
[cache_time] => 1395557635
[sponsorship_id] => 3 (sponsorships.sponsorship_id) [see in the result from before I got sponsorship_id 1 and not 3 or 4 as it should be]
[maxbid] => 20 (MAX(`sponsorships`.`bid`))
)
因此,我当前遇到的问题是,我获得了最高出价,并且从赞助表中每台服务器仅获得一个条目,这正是我想要的。但我遇到的问题是 maxbid
来自 sponsorship_id
之外的另一行。那么,如何确保我从与 maxbid
同一行获取 sponsorship_id
呢?
最佳答案
我假设您希望在 LIMIT 3 中找到出价最高的前 3 个服务器。最好将服务器表放在连接的左侧,并使用双重嵌套查询来查找每个服务器的最高出价,并从赞助表中获取具有最高出价的 ID。
SELECT `servers`.*, c.`sponsorship_id`, c.`maxbidNQ` as maxbid
FROM `servers`
RIGHT JOIN (select `server_id`,`sponsorship_id`, MAX(`bid`) as maxbidNQ from (select * from `sponsorships` WHERE `impressions` <= '1000' ORDER BY `bid` desc) d GROUP BY `server_id`) c
ON c.`server_id` = `servers`.`id`
ORDER BY maxbid DESC
LIMIT 3;
关于php - (我的)带有 MAX 和 LEFT JOIN 的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22717958/