php - (我的)带有 MAX 和 LEFT JOIN 的 SQL 查询

标签 php mysql sql

我正在使用此查询:

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

我有这两个表:

赞助

enter image description here

服务器

enter image description here

我想要这个:

[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/

相关文章:

php - 高效搜索 IP 范围 PHP 和 MySQL

mysql - JSON_CONTAINS 跨表

sql - 当表列相同时 EXCEPT 执行速度是否比 JOIN 更快

sql - R 向量转化为字符串

javascript - 在插入数据库之前删除数组的重复值

php - Laravel 保护表单隐藏字段和 url

mysql - 如何更新此 SQL 查询以提供我想要的结果?

mysql - 内部连接问题mysql

php - 从 Doctrine 地理记录中的给定坐标获取距离

php - 解析电子邮件或 html 模板的最佳方法是什么?