2011-05-05 81 views
1

嘿,我不是最大的專家與MySQL,但這裏是我迄今爲止獲得的最大entery使用MySQL來選擇最後5個條目的SUM的最大值?

SELECT DISTINCT 
      websites.id, 
      websites.title, 
      websites.url, 
      websites.screenshot, 
      impressions.number, 
      blocks.price 
    FROM websites 
LEFT JOIN blocks ON websites.id = blocks.website 
LEFT JOIN impressions ON blocks.id = impressions.block 
    WHERE status = 1 
     AND blocks.active = '1' 
     AND impressions.number = (SELECT MAX(number) 
            FROM impressions) 

我想要做的是選擇最大(數目)的總和,但最後5個條目。我嘗試過亂搞,但無法得到它。

+1

最後五個基於什麼? – 2011-05-05 23:56:30

+0

@OMG小馬,我猜最後五個印象。 – 2011-05-06 00:20:02

回答

1

要獲取最後五條記錄,它取決於您正在排序的列。讓我們假設這是一個日期列,所以後來的例子是:

SELECT MAX(n) FROM tbl ORDER BY datecol DESC limit 5; 
2

最後五個impressions.number這應該做到這一點不知道你要總結上雖然什麼

SELECT DISTINCT websites.id, 
       websites.title, 
       websites.url, 
       websites.screenshot, 
       impressions.number, 
       blocks.price 
FROM websites 
     LEFT JOIN blocks 
     ON websites.id = blocks.website 
     LEFT JOIN impressions 
     ON blocks.id = impressions.block 
WHERE status = 1 
     AND blocks.active = '1' 
ORDER BY impressions.number 
LIMIT 5 

如果你想要塊的總和,你可以做

SELECT SUM(lastblocks.price) 
    FROM (
    SELECT 
      price 
    FROM websites 
      LEFT JOIN blocks 
      ON websites.id = blocks.website 
      LEFT JOIN impressions 
      ON blocks.id = impressions.block 
    WHERE status = 1 
      AND blocks.active = '1' 
    ORDER BY impressions.number 
    LIMIT 5) lastblocks