(我的)使用MAX和LEFT JOIN进行SQL查询

时间:2014-03-28 16:13:10

标签: 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之外的另一行。那么我怎样才能确保从sponsorship_id的同一行获得maxbid

2 个答案:

答案 0 :(得分:1)

我假设你的 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;

答案 1 :(得分:0)

要从sponsorships获取每个bid具有最高server_id的行,正常模式是对内联视图执行JOIN操作,如下所示:

SELECT m.server_id
     , m.maxbid
     , o.*
  FROM ( SELECT p.server_id
              , MAX(p.bid) AS maxbid
           FROM sponsorships p
          WHERE p.impressions <= '1000'
          GROUP BY p.server_id
       ) m
  JOIN sponsorships o
    ON o.server_id = m.server_id
   AND o.bid = m.maxbid
   AND o.impressions <= '1000'

内联视图(别名为m)返回server_id的不同值以及来自具有该server_id的所有行的最大bid值。 (即每个server_id的最高出价)

使用该集合,我们可以回顾赞助商表格,并精确匹配的行。请注意,如果有多个行具有(server_id,bid)的相同值,则可能会返回多行。

然后可以将这些行连接到servers表,拉出所需的列,并添加所需的任何ORDER BY和LIMIT,例如:

SELECT s.*
     , o.sponsorship_id
     , m.maxbid
  FROM ( SELECT p.server_id
              , MAX(p.bid) AS maxbid
           FROM sponsorships p
          WHERE p.impressions <= '1000'
          GROUP BY p.server_id
       ) m
  JOIN sponsorships o
    ON o.server_id = m.server_id
   AND o.bid = m.maxbid
   AND o.impressions <= '1000'
  LEFT
  JOIN servers s
    ON s.id = m.server_id
 ORDER BY m.maxbid DESC
 LIMIT 3