Jump to content

Recommended Posts

I have got the following SELECT query which is returning false:

SELECT 
r.indicator 
FROM 
resources AS r 
WHERE 
r.stationsREF = 1 
AND 
r.record_status = 1
ORDER BY
CASE r.indicator WHEN 'P' THEN 1 WHEN 'A' THEN 2 WHEN 'R' THEN 3 WHEN 'M' THEN 4 WHEN 'C' THEN 5 ELSE 6

I know that it is the ORDER BY CASE syntax which is causing the problem because it works fine when I remove this part of the query, however the same syntax works fine on another similar query that I am using.

 

Can anybody tell me what I need to change?

 

If it is not obvious, I need to order by the r.indicator column where 'P' is listed first, 'A' second, 'R' third, 'M' fourth and anything else afterwards.

Link to comment
https://forums.phpfreaks.com/topic/212955-order-by-case/
Share on other sites

Well spotted Keith, such a silly mistake! It is at least now beign accepted as a valid query.  However, as an extension to this question, I need to amend it so that instead of the values in the r.indicator column being equal to P, A, R, M or C, I need to see if the values contain these letters.  I thought I could do this by just changing the 'P' to a '%P%' but this is not working.

 

Any suggestions?

Link to comment
https://forums.phpfreaks.com/topic/212955-order-by-case/#findComment-1109166
Share on other sites

Hi

 

Totally untested, but something like this might do it

 

SELECT 	r.indicator 
FROM resources AS r 
WHERE r.stationsREF = 1 
AND r.record_status = 1
ORDER BY
CASE TRUE WHEN r.indicator LIKE '%P%' THEN 1 WHEN r.indicator LIKE '%A%' THEN 2 WHEN r.indicator LIKE '%R%' THEN 3 WHEN r.indicator LIKE '%M%' THEN 4 WHEN r.indicator LIKE '%C%' THEN 5 ELSE 6 END

 

However if that works I suspect it might be quite slow.

 

All the best

 

Keith

Link to comment
https://forums.phpfreaks.com/topic/212955-order-by-case/#findComment-1109175
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.