使用mySql按特定顺序获取数据

5
我是一名有用的助手,可以为您翻译文本。

我正在忙着编写一个从数据库获取数据的PHP应用程序,但我需要按照特定的顺序获取数据。

我的查询如下所示

$sql = "select id,title,type from campaigns where id=$cid order by type";

现在我的问题是这些是不同的类型 'GC','MJ','MU','MS','MW','MX','GS',我希望'MX'始终会被选择为最后一个,因此它应该总是在行的末尾。所以其他的应该首先被选择,然后再选择'MX'。希望这样说得清楚了。
7个回答

15
你可以这样进行排序:
ORDER BY IF (type = 'MX', 1, 0), type

2
哇..我甚至没有最遥远的想法这是可能的。 - Erik
+1 我知道肯定有这样的东西,但是找不到相关文档。太棒了! - Michal M
解决方案很好。只是要注意大表格。如果有一个TYPE列的索引,这样做就无法利用它。 - Yada
@Roland 我不确定,但我认为是这样的。 - Greg
那在postgresql里行不通:我已添加了一个使用CASE的答案,应该可以行得通。 - davek

1
(select id,title,type from campaigns where id=$cid and type <> 'MX' order by type)
UNION
(select id,title,type from campaigns where id=$cid and type ='MX')

0
$sql = "select id,title,type from campaigns where id=$cid and type != 'MX' order by type 
union
select id,title,type from campaigns where id=$cid and type = 'MX'"; 

0

其他人已经加入SQL方法。既然您也标记了php,我还要指出您可以使用usort函数来定义自定义比较函数,供排序算法使用。

 // returns 1 if lhs > rhs, returns 0 if lhs == rhs, returns -1 if lhs <rhs
 function customCompare($lhsRow, $rhsRow)
 {
     $lhsType = $lhsRow['type']
     $rhsType = $lhsRow['type']
     // special case code so that 'MX' is always > then anything (except for another MX)
     if ($lhsType == 'MX')
     {
          if ($rhsType == 'MX')
          {
               return 0;
          }
          else
          {
               return 1;
          }
     }

     // return 1 if lhs > rhs
     if ($lhsType > $rhsType)
     {
         return 1;
     }
     else if ($rhsType < $lhsType)
     {
         return -1;
     }
     else
     {
         return 0;
     }
 }

 $rows = /*perform query without ORDER*/
 usort($rows, "customCompare");

0

你可能想要使用UNION

SELECT id, title, type
FROM campaigns
WHERE id={$cid}
AND type != 'MX'
ORDER BY type

UNION

SELECT id, title, type
FROM campaigns
WHERE id={$cid}
AND type == 'MX'

并将其作为一个查询运行。


0
...
order by case when type = 'MX' then 1 else 0 end, type

可以轻松移植到其他数据库(例如postgresql)


0
你的查询选择了多少行?看起来只有一行(我假设id是唯一的...),所以排序顺序没有影响。
除此之外,你的排序应该按照预期进行,因为按字母顺序,MX将会是列表中的最后一个。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接