8

I am trying to run an SQL Query in PHP and order by 1 column but in a certain order

i have tried this:

$sql3="SELECT * from extension
where client_id = '".$result2["id"]."' 
ORDER BY FIELD(type, 'term', 'queue', 'ivr', 'voicecentre', 'conference', 'callback', 'intercom', 'queuecentre') ";

but its just not ordering at all

M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118

8 Answers8

1

Try this. Hope use full for you.

select a.col as type,coalesce (COUNT,0) as count from
(select 'A' as col union all
select 'B' as col union all
select 'C' as col union all
select 'D' as col )a
left join Table1 T
on a.col=T.type
order by FIELD(a.col,'A','B','C','D') ;

Order by FIELD in MYSQL

SQL DEMO LINK

Community
  • 1
  • 1
Adeel Gill
  • 353
  • 4
  • 19
0

try this

  ORDER BY  case 
              when type= 'term'         then 0
              when type=  'queue'       then 1
              when type=  'ivr'         then 2
              when type=  'voicecentre' then 3
              when type=  'conference'  then 4
              when type=  'callback'    then 5
              when type=  'intercom'    then 6
              when type=  'queuecentre' then 7
          else 8
        end ASC

EDIT:

i guess you have to change the quotes here

 where client_id = '".$result2['id']."' 

LOOK DEMO FOR MY AND YOUR QUERY

EDIT2:

But if you are using gotchas sql then this function (ORDER BY FIELD) will not order properly .

look this article here and to fix it.

echo_Me
  • 37,078
  • 5
  • 58
  • 78
0

select term,queue,ivr,voicecentre,conference,callback,intercom,queuecentre from extension where client_id = '".$result2["id"]."'

please try this give the name of the field in the order you want to select

Vysakh
  • 93
  • 1
  • 11
0

$sql3=mysql("SELECT * FROM extension WHERE client_id = '".$result2["id"]."' ORDER BY (type, 'term', 'queue', 'ivr', 'voicecentre', 'conference', 'callback', 'intercom', 'queuecentre')");

0

Try and make sure the variable type is set to one of the values in the provided fieldlist.

FIELD(type, 'term', 'queue', 'ivr', 'voicecentre', 'conference', 'callback', 'intercom', 'queuecentre')
Erik Ros
  • 1
  • 5
0

The best way to do this is to use find_in_set

ORDER BY FIND_IN_SET(type, 'term,queue,ivr,voicecentre,conference,callback,intercom,queuecentre')
Ludo - Off the record
  • 5,153
  • 4
  • 31
  • 23
0
$sql3 = "SELECT * FROM extension
WHERE client_id = '".$result2["id"]."' 
ORDER BY ASC`";

this works for ordering the items with the column name you used in table.

AbcAeffchen
  • 14,400
  • 15
  • 47
  • 66
-1
SELECT *
FROM Extension,Types
WHERE Extension.typeID = Types.typeID
    AND client_id = '".$result2["id"]."' 
ORDER BY Types.order;

Table Types:

  • [typeID] => PK
  • [type]
  • [order]

Table Extension:

  • [extensionID] => PK
  • [typeID]
  • ...