views:

54

answers:

2

I have a table full of entries with DATETIME time stamps, and an ID field. I want to make a MySQL query (in my PHP script) that selects from another table with the matching ID. I want to make some kind of join that will sort by the number of entries in the first table with a timestamp more recent than 24 hours. So basically, if there are 30 entries in the first table with a timestamp of less than 24 hours with the ID "334" then I want to select the row from the second table with the ID of 334. And that should come before an entry with the ID "234" that only has 20 entries within the last 24 hours.

I hope this is clear... I'm really stumped on how to do this, so thanks for any help. :D

A: 

Try:

Select b.ColA, b.ColB, b.ColC,-- etc.
  Count(*) count
From TableB b 
   Join TableA a
     On a.Id = b.Id
        And a.TimeStamp > getDate() - 1
Group By b.ColA, b.ColB, b.ColC -- etc.
Order By Count(*) Desc

If you also want to see the rows from TableB that have no timestamps in the past 24 hours then use an outer join:

 Select b.ColA, b.ColB, b.ColC,-- etc.
  Count(*) count
 From TableB b 
   Left Join TableA a
     On a.Id = b.Id
        And a.TimeStamp > getDate() - 1
 Group By b.ColA, b.ColB, b.ColC -- etc.
 Order By Count(*) Desc
Charles Bretana
Thanks for your response! It's going to take me a while to try everything and figure out what it's doing, but I'll let you know if it works for me. Thanks again.
RobHardgood
+1  A: 

Use:

  SELECT a.*, 
         x.num
    FROM TABLE_A a
    JOIN (SELECT t.id,
                 COUNT(*) AS num
            FROM TABLE_B t
           WHERE t.timestamp BETWEEN DATE_SUB(NOW, INTERVAL 1 DAY)
                                 AND NOW()
        GROUP BY t.id) x ON x.id = a.id
ORDER BY x.num DESC
OMG Ponies
Thanks for your response too! I'll try this one out too and get back to you.
RobHardgood
@OMG Ponies: seems like you lost `= a.id` in `ON` clause. Did not you?
zerkms
@zerkms: Corrected, thx.
OMG Ponies