我如何用旧的SQLite模仿group_concat()?

时间:2014-01-20 23:50:47

标签: php sqlite group-concat

我正在使用SQLite 3.6.20,它似乎不支持group_concat,我使用的托管公司坚持不升级许多系统,所以我正在寻找模仿行为的东西。

我的表格设置和测试数据如下:

sqlite_query($db, 'CREATE TABLE ingredients (id integer primary key, name text not null, description text not null)');
sqlite_query($db, 'create table recipes (name text not null, version integer not null, ingredient_id integer not null, quantity integer not null, yield integer not null, description text not null)');

sqlite_query($db, "insert into ingredients(name, description) values('Pot', 'Tool')");
sqlite_query($db, "insert into ingredients(name, description) values('Mixing Bowl', 'Tool')");
sqlite_query($db, "insert into ingredients(name, description) values('Rutabaga', 'Morsel')");

sqlite_query($db, "insert into recipes(name, version, ingredient_id, quantity, yield, description) values ('Stock', 1, 1, 1, 3, 'Unfulfilling snack')");
sqlite_query($db, "insert into recipes(name, version, ingredient_id, quantity, yield, description) values ('Stock', 1, 2, 1, 3, 'Unfulfilling snack')");
sqlite_query($db, "insert into recipes(name, version, ingredient_id, quantity, yield, description) values ('Stock', 1, 3, 2, 3, 'Unfulfilling snack')");

我的最终结果是选择食谱的名称,产量,描述和成分,其中的成分是[Ingredients] => Pot, Mixing Bowl, Rutabaga的连续结果列表。

尝试使用coalesce()之类的东西后,最接近我能够得到的只有结果中的一个成分:

Array
(
    [Yield] => 3
    [Name] => Stock
    [Ingredients] => Pot
    [Description] => Unfulfilling snack
)
1

来自以下查询:

$query = sqlite_query($db, "select yield as Yield,
                                   name as Name,
                                   coalesce((select name 
                                             from ingredients where id in (select ingredient_id
                                                                           from recipes r2
                                                                           where name = r2.name
                                                                           and version = r2.version)
                                             ),'') as Ingredients,
                                   description as Description
                            from recipes r
                            where r.name = 'Stock'
                            and r.version = 1
                            group by Name");

缺少group_concat()可以做些什么?我宁愿不通过PHP进行文本操作来实现,但如有必要,我会这样做。

0 个答案:

没有答案