php開發中實用的兩條sql

2021-04-01 05:41:16 字數 1503 閱讀 3891

這兩天專案開發中,需要實現一些比較實用的功能,用了兩個使用的sql,總結一下,怕下次忘記了。

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

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

function getrelationtags($tagtitle,$cols="*")

else

}看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  把類似城市集中起來後按照多到少排序。

author:  heiyeluren

writetime: 2005-07-01  14:35

兩條乙個的sql

public string isalarm string userid throws userexception return result public string maprow resultset rs,int num throws sqlexception return result use...

跟日期有關的兩條經典SQL語句

1.用一條 語句得出某日期所在月份的最大天數?select day dateadd dd,day 2004 02 13 dateadd mm,1,2004 02 13 as day number 2.少記錄變成多條記錄問題 有表tbl 日期 收入 支出 2004 02 11 00 00 00 60 ...

面試時常被問到的兩條sql

一 oracle橫列轉換 行列互換 select t.from temp sc t select sc.stdname,a.grade 語文,b.grade 數學,c.grade 物理,d.grade 化學 from select distinct stdname from temp sc sc,s...