簡體   English   中英

(My)使用MAX和LEFT JOIN的SQL查詢

[英](My)SQL query with MAX and LEFT JOIN

我正在使用以下查詢:

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的行。 我有什么做的就是在sponsorship_id從maxbid?

更新#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另一行。 那么,如何才能確保我得到的sponsorship_id從同一行maxbid

我假設您要從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;

要從sponsorships獲取對每個server_id bid最高的行,通常的模式是對內聯視圖執行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的最高出價)

有了這個設置,我們可以回顧一下Sponsorships表,並細化匹配的行。 請注意,如果有多行具有相同的(server_id,bid)值,則有可能獲得多於​​一行。

然后可以將這些行連接到服務器表,拉出所需的列,並添加所需的任何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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM