Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I want to get the last(highest) ID of every User_ID, my code works fine but I also want to order it by descending

ID User_ID
1 150
2 150
3 151
4 151

PHP
$result = $this->link->query("SELECT * FROM tickets WHERE ID IN (SELECT MAX(ID) FROM tickets WHERE Type=0 GROUP BY User_ID)");


top query gives me:
ID User_ID
2 150
4 151

and here is what I want:

ID User_ID
4 151
2 150


When I add ORDER BY ID DESC, it should give me 3,2,1 for example, but it gives me 1,2,3 by default.

PHP
$result = $this->link->query("SELECT * FROM tickets WHERE ID IN (SELECT MAX(ID) FROM tickets WHERE Type=0 GROUP BY User_ID ORDER BY ID DESC)");


I'd be very happy if you help me :D I was searching the internet about 10 hours and I couldn't find any solution.

Thanks.
Posted
Updated 13-Apr-15 17:01pm
v2

You have used order by on the inner query.
Change the location of the closing bracket - try SELECT * FROM tickets WHERE ID IN (SELECT MAX(ID) FROM tickets WHERE Type=0 GROUP BY User_ID) ORDER BY ID DESC
 
Share this answer
 
v2
Comments
[no name] 13-Apr-15 23:15pm    
Dear Abhinav S, I've already done that, but same result...
[no name] 13-Apr-15 23:21pm    
The problem caused because of DataTable, thnaks
No need to do subquery. Try this-
PHP
$result = $this->link->query("SELECT MAX(ID) AS ID,User_ID FROM tickets WHERE Type=0 GROUP BY User_ID ORDER BY ID DESC)");

This should do your job.
Hope, it helps :)
 
Share this answer
 
Not sure if I understood the requirement correctly but based on your example if you want user id 151 before 150 then you should have two sorting columns. Something like:
PHP
$result = $this->link->query("SELECT * FROM tickets WHERE ID IN (SELECT MAX(ID) FROM tickets WHERE Type=0 GROUP BY User_ID)  ORDER BY USER_ID DESC, ID DESC");

Also check that you don't sort the data somewhere in the code after getting it from the database.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900