在項目中靈活運用合適的排序方法(Sphinx,SQL,Yii,數組)mysql中替代charindex的函數substring_index、find_in_set

來源:互聯網
上載者:User

本文總結一下最近項目中用到的各種排序方法,如需轉載,請註明文章出處


1,Sphinx排序

 

 

        Yii::import('ext.SphinxClient');        $sphinxapi = new SphinxClient();        $sphinxapi->SetServer('127.0.0.1', 10312);        $sphinxapi->SetConnectTimeout(3);        $sphinxapi->SetMatchMode(SPH_MATCH_BOOLEAN);        $sphinxapi->SetArrayResult(true);        $sphinxapi->SetGroupBy('type', SPH_GROUPBY_ATTR,"@count desc");        $sphinxapi->SetLimits(0, 9999, 10000);        $result = $sphinxapi->Query('', 'main;delta');        unset($sphinxapi);

其中

 SPH_GROUPBY_ATTR,"@count desc"

指定了按照 @count 降序排列

 


2,SQL排序(讓某一列根據指定的數組排序,而不是本表欄位)

         

有時候我們需要從資料庫中找到的資料按照我們已有的數組順序進行排列,而不是簡單的根據資料表欄位進行 order by

比如:

我們有一個數組 $IDArray=array(13,24,2,23,21,10,22,12,26,27,19,20,8,14,25,9,11,1,6);

現在需要從shop表中尋找19個資料,並且讓shop的id根據$IDArray中的順序來排列

可以使用,find_in_set(id,'************')來實現

 

SELECT id, name FROM shop WHERE id IN(13,24,2,23,21,10,22,12,26,27,19,20,8,14,25,9,11,1,6) order by find_in_set(id,'13,24,2,23,21,10,22,12,26,27,19,20,8,14,25,9,11,1,6')

當然,我們遇到的常常是動態情況,這是可以用數組->字串的法寶 join

 

 

$sql = "SELECT id, name FROM shop WHERE id IN(".join(',', array_keys($IDARRAY)).") order by  find_in_set(id,'".join(',', array_keys($IDARRAY))."') ";$rawDataAll = Yii::app()->db->createCommand($sql)->queryAll();

 

關於find_in_set(id,'************'),的用法擴充可以

參考:mysql中替代charindex的函數substring_index、find_in_set


3,Array數組根據自己的任意元素進行排序


把這個方法封裝成一個類,在Yii項目中隨意調用

 

ArrayHelper::array_sort($bodyArray, 'count', 'desc')

 

 

<?phpclass ArrayHelper extends CController{    public function array_sort($arr, $keys, $type='asc')    {        $keysvalue = $new_array = array();        foreach($arr AS $k=>$v)        {            $keysvalue[$k] = $v[$keys];        }        if($type == 'asc')        {            asort($keysvalue);        }        else        {            arsort($keysvalue);        }        reset($keysvalue);        foreach ($keysvalue as $k=>$v)        {            $new_array[$k] = $arr[$k];        }        return $new_array;    }}?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.