PHP開發中實用的兩條SQL_PHP教程

來源:互聯網
上載者:User
這兩天項目開發中,需要實現一些比較實用的功能,用了兩個使用的sql,總結一下,怕下次忘記了。

1. 檢索資料庫中跟提交的內容相匹配的內容

比如:提交的資料是“遊泳”,那麼資料庫中有“我喜歡遊泳”字樣的就算是匹配,但是這樣一來,還是不夠,比如我提交的是“周末去遊泳”,資料庫中有“遊泳”的內容,其實意思類似,但是卻使用like找不到的,於是想到下面的sql,已經封裝成函數了:

function getRelationTags($tagTitle,$cols="*")
{
$titleFeildStrLen = 24; //3*8 四個漢字或者24個字元.
if ("" == $tagTitle) return false;

$sql = "select $cols from ".$TableName." where title != '' and (LOCATE(title,'$tagTitle') or ((issystem = 1 or LENGTH(title) <= $titleFeildStrLen) and title like '%".$tagTitle."%' )) order by LENGTH(title) ";
$data =& $db->getAll($sql);
if(DB::isError($data)){
return $this->returnValue($data->getMessage());
}else{
return $data;
}
}

看sql:

select $cols from ".$TableName." where title != '' and (LOCATE(title,'$tagTitle') or ((issystem = 1 or LENGTH(title) <= $titleFeildStrLen) and title like '%".$tagTitle."%' )) order by LENGTH(title)

其實就是兩次匹配,一次是正向匹配,就是把提交的標籤跟資料庫中標籤進行匹配,第二次是把資料庫中的標籤跟提交的標籤進行匹配。

要害在LOCATE()函數,同時也限制了長度,因為mysql中的編碼是:

set names 'utf8'

就是是utf8的,那麼一個漢字要佔用3個位元組,字元只佔用1個位元組,所以上面的:

$titleFeildStrLen = 24;

就是8個漢字和24個字元範圍那的標籤進行匹配。


2. 同類排序

資料庫中比如是這樣的內容:

北京 1023 1

天津 2301 1

上海 3450 1

天津 4520 1

北京 3902 1

那麼我要提取所有的城市資料,並且把每種城市資料的總數跟別的城市總數進行比較後排序。

函數代碼如下:

function getMostCity($num)

{

$sql = "select count(id) as num,city from ".$TableName." where city != '' group by city order by num desc limit 0,$num;";

$data =& $db->getAll($sql);

if($db->isError($data))

return false;

else

return $data;

}

我們關注一下上面的sql語句:

select count(id) as num,city from ".$TableName." where city != '' group by city order by num desc limit 0,$num

核心就是 group by city 把類似城市集中起來後按照多到少排序。

http://www.bkjia.com/PHPjc/631404.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/631404.htmlTechArticle這兩天項目開發中,需要實現一些比較實用的功能,用了兩個使用的sql,總結一下,怕下次忘記了。 1. 檢索資料庫中跟提交的內容相匹配的...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.