简体   繁体   中英

MySQL order by field in certain order

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

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

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.

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

$ sql3 = mysql(“ SELECT * FROM extension WHERE client_id ='”。$ result2 [“ id”]。“'ORDER BY(类型,'term','queue','ivr','voicecentre','conference' ,“回叫”,“对讲机”,“队列中心”)“);

尝试确保变量类型设置为提供的字段列表中的值之一。

FIELD(type, 'term', 'queue', 'ivr', 'voicecentre', 'conference', 'callback', 'intercom', 'queuecentre')

最好的方法是使用find_in_set

ORDER BY FIND_IN_SET(type, 'term,queue,ivr,voicecentre,conference,callback,intercom,queuecentre')
$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.

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]
  • ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM