Link to home
Start Free TrialLog in
Avatar of cbielich
cbielichFlag for United States of America

asked on

Group By and Order By in same MySQL statement not working

Here is my query:

$sql = "SELECT * FROM messages LEFT JOIN users ON messages.from_id = users.ID WHERE messages.to_id = '$session_user_id' AND messages.hide != '$session_user_id' GROUP BY messages.message_id ORDER BY messages.timestamp DESC";

I already know that using Group By and Order By in the same statement does not work, I have read some solutions but can seem to rewrite is successfully to make it work, can someone help me please?

I know an INNER JOIN needs to be in there, but since I am already using a LEFT JOIN I am having a hardtime using the two different joins in the same statement.
Avatar of Om Prakash
Om Prakash
Flag of India image

instead of *, specify the field name that will be part of group.

Example:
select title, count(*) AS Number
from employee
GROUP BY title
ORDER BY Number;
Avatar of cbielich

ASKER

I have several fields that I need to pull, can I add them all?
Avatar of Sharath S
Can you try this?
$sql = "SELECT * FROM (SELECT * FROM messages LEFT JOIN users ON messages.from_id = users.ID WHERE messages.to_id = '$session_user_id' AND messages.hide != '$session_user_id' GROUP BY messages.message_id) as t1 ORDER BY timestamp DESC";

Open in new window

errors out
Can you post your error message?

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in

Open in new window

Are you able to execute without Order By clause?
same error
try:

$sql = "SELECT * FROM messages LEFT JOIN users ON messages.from_id = users.ID WHERE messages.to_id = '$session_user_id' AND messages.hide <> '$session_user_id' GROUP BY messages.message_id ORDER BY messages.timestamp DESC";

?
Pulls up the record the same as my script, no order to it
What is your MySQL version? Are you getting error without ORDER BY clause also?
Server Version: 5.0.91
No Error without Order By Clause
ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
dont think so I use it all the time, I also tried using ID as order by that did not work.
pls also post the scripts including part of mysql_fetch_array() so that we got better clues to resolve your problem.