SQLite是一个轻量级引擎,尤其在PHP中内置的2版本,并不带有类似MySQL那样的实用函数。
但是它提供了一套非常灵活的自定义函数方式。用户可以将需要使用的功能,先用PHP函数实现,然后注册到SQLite里面,就可以在SQL语句中使用了。
一个最简单的例子:
function url2host($url) {
$parts = parse_url($url);
return "$parts[scheme]://$parts[host]";
}
// Tell SQLite to associate PHP function url2host( ) with the
// SQL function host( ). Say that host( ) will only take 1 argument.
sqlite_create_function($db, 'host', 'url2host', 1);
// Do the query
$r = sqlite_query($db, 'SELECT DISTINCT host(lower(url)) AS clean_host
FROM access_log ORDER BY clean_host;');
SQLite只支持Count,不支持Averag。所以类似功能也要写函数实现。
因为需要对多项结果进行累加,注册方式与普通函数注册不同。注意:请严格按照格式进行书写。看起来似乎很复杂,但是如果你用过array_walk,就会感觉到似曾相识了。
// average_step( ) is called on each row.
function average_step(&$existing_data, $new_data) {
$existing_data['total'] = $new_data;
$existing_data['count'] ;
}
// average_final( ) computes the average and returns it.
function average_final(&$existing_data) {
return $existing_data['total'] / $existing_data['count'];
}
//regist average , using average_step and average_final
sqlite_create_aggregate($db, 'average', 'average_step', 'average_final');
$r = sqlite_query($db, 'SELECT average(number) FROM numbers');
需要注意的是: SQLite对COUNT的语法支持与MySQL不同。
MySQL: select class, count(*) as cnt group by class where cnt > 3
SQLite: select class, count(*) as cnt group by class HAVING cnt >3
印象里面SQL2的规范方式就是这样的,只是MySQL为了方便更灵活处理了而已。
另外,对于自定义函数,还有一点需要说明:
如果数据是二进制(比如图象),需要进行解码和编码处理。因为函数是在SQLite内部运行的,二进制数据在SQLite内部是编码存储的。
$data = sqlite_udf_binary_decode($encoded_data);
.... .... //deal with $data
$result = sqlite_udf_binary_encode($return_value);
~~呵呵~~
新闻热点
疑难解答