HOW TO ORDER BY with certain results first similar to sponsors links idea
Please, advise on proper query:
I am looking to select results from the table, but I want to show all results by particular ID first, then everyone else, sort of like you would see "sponsored links" first.
10 users with incremental IDs from 1 to 10.
Each has multiple listings of widgets in the widgets tables. Each widget is associated with user ID.
I want to select all widgets from the widgets table based on whatever condition I have, but I want to display results for particular user with ID=6 first. so results would be something like this:
USER_ID | WIDGET TITLE |
6 | AASDF
6 | CASDF
6 | WFDS
1 | ASDF
2 | ASDF
2 | FDA
3 | ASDF
4 | ASDF
4 | FDS2
4 | ASDASSF
4 | ASDDF
5 | QWER
7 | QWET
8 | ASDF
9 | FDAS
10 | XX
10 | XXX
So it is almost as if I am trying to write the following (I know it is not right I am trying to flow the logic here for demonstration of what I am looking to do):
SELECT * FROM `widgets` ORDER BY `USER_ID` (WHERE `USER_ID` = '6' FIRST, THEN ORDER BY `USER_ID` WHERE `USER_ID` != 6 ASC)
Can it be done with one query? I can't seem to find a suitable answer.
Create a temp table with all the columns you wish to select, then SELECT into the table those records with the ID you want, then SELECT into the table all the other records (without the ID) sorted by ID, then SELECT from the temp table without specifying any kind of ORDER BY clause.
Not tested, but it seems correct. The temp table (if properly created) will be nulled when the query is over.
Awesome. Why didn't I think of that ?
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread