views:

60

answers:

1

Hey guys,

I have 3 tables with a column in each which relates to one ID per row. I am looking for an sql statement query which will check all 3 tables for any rows in the last 24 hours (86400 seconds) i have stored timestamps in each tables under column time.

After I get this query I will be able to do the next step which is to then check to see how many of the ID's a reoccurring so I can then sort by most popular in the array and limit it to the top 5...

Any ideas welcome! :)

Thanks in advanced.

Stefan

+9  A: 
SELECT  id, COUNT(*) AS cnt
FROM    (
        SELECT  id
        FROM    table1
        WHERE   time >= NOW() - INTERVAL 1 DAY
        UNION ALL
        SELECT  id
        FROM    table2
        WHERE   time >= NOW() - INTERVAL 1 DAY
        UNION ALL
        SELECT  id
        FROM    table3
        WHERE   time >= NOW() - INTERVAL 1 DAY
        ) q
GROUP BY
        id
ORDER BY
        cnt DESC
LIMIT 5
Quassnoi
Holy crap. I've heard of MySQL ninjas, but I don't think I've ever met one.
dclowd9901
Just testing this :) Two seconds!
Stefan
It hasnt given any errors but I am not getting any results? I use php time() function on storing the timestamp into the time column in each table... hmmm any ideas? Thanks again! This query in short will count which id has the most occurrences in the last 24 hours with relation to its timestamp and then return the top 5 correct?
Stefan
u can try -> WHERE time BETWEEN strtotime("now") AND strtotime("-1 day")
nik
GOT IT! i had to convert unixtimestamp to date: FROM_UNIXTIME( `time` ) :) Thanks alot!
Stefan