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
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. 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
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
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;
精彩评论