LoginSignup
0
0

More than 5 years have passed since last update.

SQLite(3.5.4以前)でgroup_concat(PHPから使う場合)

Posted at

SQLiteはバージョン3.5.4から便利な集約関数group_concatが使用できるようになりました。
逆に言えば、それより前のバージョンでは当然のことながら使うことはできません。
そこで、ユーザ定義関数(UDF)の出番です。

今回は、PHP5.1以降に標準で入っているPDOでgroup_concatを追加します。

group_concat.php
// $dbにはSQLiteのPDOオブジェクトが入っているものとする。
function createGroupConcat($db)
    if (version_compare($db->getAttribute(PDO::ATTR_SERVER_VERSION), '3.5.4')<0) {
        $step_func = create_function('&$context, $rownumber, $string, $delimiter=\',\'', 'if (isset($string)) { if (isset($context)) $context .= $delimiter; $context .= $string; } return $context;');
        $finalize_func = create_function('&$context, $rownumber', 'return $context;');
        $db->sqliteCreateAggregate('group_concat', $step_func, $finalize_func);
    }
}

一応補足しておきますと、登録したgroup_concatが使えるのはユーザ関数を追加したPDOオブジェクトだけです。

SQLite3.5.4以降では登録処理をスキップしているので、元々あるgroup_concatをそのまま残します。
SQLite3.3.7で確認していますが、SQLite2系列でもできるかどうかは調べていません。

(昔自分のサイトで書いたやつの再掲です。)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0