Go Back   CodingForums.com > :: Server side development > MySQL

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 08-22-2012, 05:34 AM   PM User | #1
bubaphex
New to the CF scene

 
Join Date: Sep 2007
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
bubaphex is an unknown quantity at this point
Union Order By Question

Hi All,

Im trying to order my query in two places, the first select, and the second select.

I dont wish to order my query as a whole.

My query:

SELECT * FROM jos_content WHERE introtext LIKE 'something' AND state = '1' UNION ALL SELECT * FROM jos_content WHERE state = '1'

Basicly i want something like this:

SELECT * FROM jos_content WHERE introtext LIKE 'something' AND state = '1' ORDER BY created DESC UNION ALL SELECT * FROM jos_content WHERE state = '1' ORDER BY created DESC

Could any one shed some light on this?

Any help will be much appreciated
bubaphex is offline   Reply With Quote
Old 08-22-2012, 02:42 PM   PM User | #2
guelphdad
Super Moderator


 
guelphdad's Avatar
 
Join Date: Mar 2006
Location: St. Catharines, Ontario Canada
Posts: 2,629
Thanks: 4
Thanked 147 Times in 138 Posts
guelphdad will become famous soon enoughguelphdad will become famous soon enough
So really what you want is introtext that matches a certain word to come before the others and state=1 in either case?

Code:
SELECT
  foo,
  bar,
  qux
FROM
  jos_content
WHERE
  state=1
ORDER BY
  CASE WHEN introtext LIKE '%something%' THEN 0 ELSE 1 END,
  created DESC
The CASE expression puts all the rows where you match the word you are looking for in introtext before the non matching rows and then orders them by created descending in both cases.

By the way it may have only been your example but if you are looking for an exact match then you use = if you are using LIKE then you are looking for a word in introtext that either has text before or after it, thus the wild cards i've added.

The other thing i've done is removed quotes from around numeric data.
guelphdad is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 07:43 AM.


Advertisement
Log in to turn off these ads.