简体   繁体   中英

PHP / MySQL - Construct a SQL query

Im having a little trouble constructing a query.

I have a table with 3 columns.

id - day - pageviews

What i basically want to do is get 8 id's from the table where the pageviews are the highest from the last 60 days.

The day column is a datetime mysql type.

Any help would be great, im having a little trouble figuring this one out.

Cheers,

Do something like this:

SELECT id FROM table_name
WHERE DATE_SUB(CURDATE(),INTERVAL 60 DAY) <= day
ORDER BY pageviews DESC
LIMIT 8;

Almost the same as TuteC posted, but you'll need a group by to get what you need...

SELECT id, SUM(pageviews) totalViews
FROM table
WHERE DATE_SUB(CURDATE(), INTERVAL 60 DAY) <= day
GROUP BY id
ORDER BY totalViews DESC
LIMIT 8
$sixtyDaysAgo = date('Y-m-d',strtotime('-60 days'));

$sql = "SELECT id
        FROM table_name
        WHERE day >= '$sixtyDaysAgo 00:00:00'
        ORDER BY pageviews DESC
        LIMIT 8";

If each row is a number of pageviews for that day, and you're looking for the highest total sum of 60 days' worth, then you'll need to total them all and then grab the top 8 from among those totals, like so:

$sql = "SELECT id
        FROM (
            SELECT id, SUM(pageviews) AS total_pageviews
            FROM table_name
            WHERE day >= '$sixtyDaysAgo 00:00:00'
            GROUP BY id
        ) AS subselect
        ORDER BY total_pageviews DESC
        LIMIT 8";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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