0

I writing a code to get mysql field values sorted. my filed values are as below

**downloads**
N/A
10

50
30
unlimited
N/A
70
unlimited

those are on mysql table field. i need to sort those assenting and descending like below

Assending
N/A

10
30
50
70
unlimited
unlimited


Desending
unlimited
unlimited
70
50
30
10

N/A

The space is some rows don't have data. i wrote mysql query like below

SELECT * FROM fltable  ORDER BY LENGTH(downloads), downloads DESC

But this not returns correct sort, can anyone help me with this using my sql or php solution. Thank You

4

4 回答 4

2

对于赋值使用:

SELECT downloads, (CASE WHEN downloads = 'N/A' THEN 0 
                        WHEN downloads = '' THEN 1 
                        WHEN downloads='unlimited' THEN 4 
                        ELSE 3 END) as rank 
       FROM fltable 
       ORDER BY rank ASC;

对于降值使用:

SELECT downloads, (CASE WHEN downloads = 'N/A' THEN 0 
                        WHEN downloads = '' THEN 1 
                        WHEN downloads='unlimited' THEN 4 
                        ELSE 3 END) as rank 
       FROM fltable 
       ORDER BY rank, downloads DESC;
于 2013-09-03T10:56:51.657 回答
1
SELECT * FROM fltable  
ORDER BY case when downloads = 'N/A' then 1
              when downloads is null then 2
              when downloads = 'unlimited' then 4
              else 3
         end DESC, 
         downloads * 1 DESC
于 2013-09-03T10:36:31.733 回答
0
  • 我知道,这个解决方案与 SQL 中的另一个解决方案非常相似。

您可以使用usort来实现您需要的任何逻辑。

define('DV_NA', 1);
define('DV_EMPTY', 2);
define('DV_NUM', 3);
define('DV_UNLIMITED', 4);
define('DV_OTHER', 5);

function customDloadValue($n) {
  switch($n) {
  case "N/A": return DV_NA;
  case null: case "": return DV_EMPTY;
  case "unlimited": return DV_UNLIMITED;
  default: return is_numeric($n) ? DV_NUM : DV_OTHER;
  }
}

usort($strings, function ($a, $b) {
  $av = customDloadValue($a);
  $bv = customDloadValue($b);
  if ($av != DV_NUM or $bv != DV_NUM) return $av - $bv;
  return intval($a) - intval($b)
});
于 2013-09-03T10:46:54.473 回答
0

另一种类似的方式:

SELECT download, (download= 'N/A') boolNA, (download= '') boolBlank, 
       (download+0 > 0) boolNum, (download= '0') boolZero 
FROM table 
ORDER BY boolNA DESC, boolBlank DESC, boolZero DESC, boolNum DESC, 
         (download+0), download

这样,您可以创建要排序的组。

这可能会导致类似:

N/A

10
30
50
70
unlimited
unlimited

与上述相同的结果,不同的方式。如果您只有几个需要分组的数据类型(少于 3 个),可能会更容易。

于 2013-10-29T14:46:21.247 回答