简体   繁体   English

使用MySQL选择最后5个条目的SUM的最大值?

[英]Using MySQL to SELECT the MAX of a SUM of the last 5 entries?

Hey, I'm not the biggest expert with MySQL but here is what I have so far to get the MAX entery 嘿,我不是MySQL的最大专家,但到目前为止,这是我获得MAX Entery的全部内容

   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)

What I want to do is SELECT the max(number) but of the sum of the last 5 entries. 我想做的是选择max(number),但要选择最后5个条目的总和。 I've tried messing around but just can't get it. 我已经尝试弄乱了,但无法理解。

The last five impressions.number this should do it don't know what you want to sum on though 最后五个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 

If you wanted to sum of blocks.price you could just do 如果您想对blocks.price求和,则可以这样做

 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

To get the last five records, it depends on the column by which you are sorting. 要获取最后五个记录,它取决于您要排序的列。 Let's assume this is a date column, so then an example would be: 假设这是一个日期列,那么一个例子是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM