Buchead Posted October 27, 2007 Share Posted October 27, 2007 Hello all, I'm having some trouble obtaining a order a result based on a count. I have 2 tables - customers (id, name) and bookings (bookid, custID, date) - and want to order the output depending upon a request. The problem lies in that not all the customers may have placed a booking, yet they are still required to be shown with a count of 0. I can get the query working via phpmyadmin using the command: SELECT count(b.date) AS theCount, c.* FROM customers AS c LEFT JOIN booking AS b ON b.custID = c.id GROUP BY b.custID ORDER BY theCount ASC (or changing this to DESC as required). Yet when I put it into the php it doesn't work. Clearly I'm missing something obvious but can't see it myself. In php I've tried the following just in case (in fact tried swapping line around a lot) but it also (unsurprisingly) fails: SELECT c.* FROM customers AS c LEFT JOIN booking AS b ON b.custID = c.id GROUP BY b.custID ORDER BY COUNT(b.date) ASC Thanks for any pointers, Clive. Quote Link to comment https://forums.phpfreaks.com/topic/75022-solved-problem-using-order-and-group/ Share on other sites More sharing options...
Barand Posted October 27, 2007 Share Posted October 27, 2007 I'd group by c.id. Does that help. <?php $sql = "SELECT count(b.date) AS theCount, c.* FROM customers AS c LEFT JOIN booking AS b ON b.custID = c.id GROUP BY c.id ORDER BY theCount ASC"; $res = mysql_query($sql); while ($row = mysql_fetch_assoc($res)) { echo $row['id'], ':', $row['theCount'], '<br/>'; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/75022-solved-problem-using-order-and-group/#findComment-379369 Share on other sites More sharing options...
Buchead Posted October 27, 2007 Author Share Posted October 27, 2007 Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/75022-solved-problem-using-order-and-group/#findComment-379371 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.