Trouble using ORDER BY in a UNION statement

Thread Solved

Join Date: Oct 2007
Posts: 260
Reputation: Venom Rush is an unknown quantity at this point 
Solved Threads: 2
Venom Rush's Avatar
Venom Rush Venom Rush is offline Offline
Posting Whiz in Training

Trouble using ORDER BY in a UNION statement

 
0
  #1
Oct 8th, 2009
As the title suggests, I'm having trouble sorting the results of a union statement. I'm trying to sort the results by date descending and it's coming out ascending.

  1. (SELECT a, b, c, d, e, f, DATE FROM table1 WHERE a=10 AND b=1) UNION (SELECT a, b, c, d, e, f, DATE FROM table1 WHERE a=11 AND b=1) ORDER BY DATE DESC;
I'm selecting all the same rows from the same table. The reason I'm using a UNION statement is because I have 3 different WHERE conditions.

This really should work and I've gone over my code with a fine tooth comb. It's driving me crazy. Anyone have any suggestions?
This user has a spatula. We don't know why, but we are afraid.
Reply With Quote Quick reply to this message  
Join Date: Sep 2008
Posts: 123
Reputation: cgyrob is on a distinguished road 
Solved Threads: 18
cgyrob's Avatar
cgyrob cgyrob is offline Offline
Junior Poster
 
0
  #2
Oct 8th, 2009
Try this

  1. SELECT a,b,c,d,e,f FROM
  2. (
  3. (SELECT a, b, c, d, e, f, DATE
  4. FROM table1 WHERE a=10 AND b=1)
  5. UNION
  6. (SELECT a, b, c, d, e, f, DATE
  7. FROM table1 WHERE a=11 AND b=1)
  8. )
  9. ORDER BY DATE DESC

You need to encapsulate the whole union to order them after all the records are retrieved.
Last edited by cgyrob; Oct 8th, 2009 at 12:19 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2007
Posts: 260
Reputation: Venom Rush is an unknown quantity at this point 
Solved Threads: 2
Venom Rush's Avatar
Venom Rush Venom Rush is offline Offline
Posting Whiz in Training
 
0
  #3
Oct 8th, 2009
Originally Posted by cgyrob View Post
Try this

  1. SELECT a,b,c,d,e,f FROM
  2. (
  3. (SELECT a, b, c, d, e, f, DATE
  4. FROM table1 WHERE a=10 AND b=1)
  5. UNION
  6. (SELECT a, b, c, d, e, f, DATE
  7. FROM table1 WHERE a=11 AND b=1)
  8. )
  9. ORDER BY DATE DESC

You need to encapsulate the whole union to order them after all the records are retrieved.
Hi cgyrob

Thanks for the response. My original statement is actually correct. I was being blonde and didn't change a class variable on my display page which was causing the issues.
This user has a spatula. We don't know why, but we are afraid.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



Tag cloud for MySQL
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC