MySQL按特定顺序按字段排序

时间:2014-02-21 10:17:16

标签: php mysql sql

我正在尝试在PHP中运行SQL查询并按1列排序,但按特定顺序

我试过这个:

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

但它根本就没有订购

8 个答案:

答案 0 :(得分:1)

试试这个。希望充分利用你。

  

选择a.col作为类型,合并(COUNT,0)为count   来自   (选择'A'作为col union all   选择'B'作为col union all   选择'C'作为col union all   选择'D'作为col)a   左连接表1 T
  在a.col = T.type
  按FIELD排序(a.col,'A','B','C','D');

Order by FIELD in MYSQL

SQL DEMO LINK

答案 1 :(得分:0)

试试这个

  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

编辑:

我想你必须在这里更改引号

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

LOOK DEMO FOR MY AND YOUR QUERY

<强> EDIT2:

但如果您使用的是陷阱sql,则此函数(ORDER BY FIELD)将无法正确排序。

查看此article here并进行修复。

答案 2 :(得分:0)

从分机中选择term,queue,ivr,voicecentre,conference,callback,intercom,queuecentre 其中client_id ='“。$ result2 [”id“]。”'

请尝试按照您要选择的顺序提供字段名称

答案 3 :(得分:0)

$ sql3 = mysql(&#34; SELECT * FROM extension WHERE client_id =&#39;&#34;。$ result2 [&#34; id&#34;]。&#34;&#39; ORDER BY(类型,&#39; term&#39;,&#39; queue&#39;,&#39; ivr&#39;,&#39; voicecentre&#39;,&#39; conference&#39;,& #39;回拨&#39;,&#39; intercom&#39;,&#39; queuecentre&#39;)&#34;);

答案 4 :(得分:0)

尝试并确保将变量类型设置为提供的字段列表中的某个值。

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

答案 5 :(得分:0)

执行此操作的最佳方法是使用find_in_set

ORDER BY FIND_IN_SET(type, 'term,queue,ivr,voicecentre,conference,callback,intercom,queuecentre')

答案 6 :(得分:0)

$sql3 = "SELECT * FROM extension
WHERE client_id = '".$result2["id"]."' 
ORDER BY ASC`";

这适用于使用您在表中使用的列名对项目进行排序。

答案 7 :(得分:-1)

SELECT *
FROM Extension,Types
WHERE Extension.typeID = Types.typeID
    AND client_id = '".$result2["id"]."' 
ORDER BY Types.order;

表类型:

  • [typeID] =&gt; PK
  • [式]
  • [指令]

表扩展名:

  • [extensionID] =&gt; PK
  • [TYPEID]
  • ...
相关问题