【问题标题】:How to return array of foreign rows in SQLITE?如何在 SQLITE 中返回外部行数组?
【发布时间】:2020-04-29 15:12:06
【问题描述】:

首先,我的 SQL 技能充其量只是边际。我正在使用 SQLite 数据库,并且我想避免使用太多过滤函数使我的应用程序代码混乱。我正在寻找的是将另一个表的多行集成到一个数组中的 SQL 语句。我已经搜索了很长时间,但我什至不确定正确的关键字是什么。

不管怎样,这些都是我的桌子......

CREATE TABLE table_a (identifier PRIMARY KEY, name TEXT UNIQUE);
CREATE TABLE table_b (identifier PRIMARY KEY, name TEXT UNIQUE, fk_a INTEGER, FOREIGN KEY(fk_a) REFERENCES table_a(identifier);

table_a:

1 | ABC
2 | DEF
3 | GHI

table_b:

1 | abc | 1
2 | def | 1
3 | ghi | 2

...现在我正在寻找一个语句,它返回 table_a 中的一行,其中包含一个数组中 table_b 中的所有相应行:

1 | ABC | [1 | abc | 1, 2 | def | 1]

这可能吗?如果是……最简洁的写法是什么?

提前致谢!

【问题讨论】:

    标签: sql arrays sqlite select


    【解决方案1】:

    我想你想要group_concat():

    select a.identifier, a.name,
      '[' || group_concat(b.identifier ||  ' | ' ||  b.name ||  ' | ' || b.fk_a) || ']' col
    from table_a a left join table_b b
    on b.fk_a = a.identifier
    group by a.identifier, a.name;
    

    请参阅demo
    结果:

    | identifier | name | col                       |
    | ---------- | ---- | ------------------------- |
    | 1          | ABC  | [1 | abc | 1,2 | def | 1] |
    | 2          | DEF  | [3 | ghi | 2]             |
    | 3          | GHI  |                           |
    

    或者如果你喜欢json_group_array():

    select a.identifier, a.name,
      json_group_array(b.identifier ||  ' | ' ||  b.name ||  ' | ' || b.fk_a) col
    from table_a a left join table_b b
    on b.fk_a = a.identifier
    group by a.identifier, a.name;
    

    请参阅demo
    结果:

    | identifier | name | col                           |
    | ---------- | ---- | ----------------------------- |
    | 1          | ABC  | ["1 | abc | 1","2 | def | 1"] |
    | 2          | DEF  | ["3 | ghi | 2"]               |
    | 3          | GHI  | [null]                        |
    

    你可以使用:

    replace(json_group_array(b.identifier ||  ' | ' ||  b.name ||  ' | ' || b.fk_a), '"', '')
    

    如果你不想要双引号。

    【讨论】:

    • 伙计,非常感谢!通过使用 'json_group_object' 会变得更好。只需要弄清楚如何启用 json_* 功能,但我猜这不会是一个问题——它在小提琴中完美地工作。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2023-02-23
    • 2015-02-27
    • 2021-08-24
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 2018-11-13
    相关资源
    最近更新 更多