sql - 如何使用 sqlite 中的 View 在特定行中添加列?

标签 sql database sqlite view

我在 sqlite 的数据库中有 3 个表

Table A

<br/>+-----+-------+
|  id | name  |
+-----+-------+
| 1   | Ann   |
| 2   | Bill  |
| 3   | Mike  |
| 4   | Zoey  |
+-----+-------+

Table B

+-----+-----+
| idA | idC |
+-----+-----+
| 1   | 1   |
| 1   | 2   |
| 2   | 3   |
| 3   | 2   |
| 4   | 1   |
+-----+-----+

Table C

+-----+-----+
|  id | type|
+-----+-----+
| 1   | x   |
| 2   | y   |
| 3   | z   |
+-----+-----+<br/>

我已经尝试过:

CREATE VIEW test AS SELECT A.id, A.name, C.type
FROM A, B, C
WHERE B.idA = A.id
AND B.idB = B.id

然后我得到:


**View test**
+-----+-------+-------+
|  id | name  | type  |
+-----+-------+-------+
| 1   | Ann   | x     |
| 1   | Ann   | y     |
| 2   | Bill  | z     |
| 3   | Mike  | y     |
| 4   | Zoey  | x     |
+-----+-------+-------+

但是我想做这样的事情

+-----+-------+-------+
|  id | name  | type  |
+-----+-------+-------+
| 1   | Ann   | x,y   |
| 2   | Bill  | z     |
| 3   | Mike  | y     |
| 4   | Zoey  | x     |
+-----+-------+-------+

不重复任何行,这可能吗?

最佳答案

SQLite 支持GROUP_CONCAT()

CREATE VIEW test 
AS
SELECT  A.id, A.name, GROUP_CONCAT(C.type) AS Type
FROM    A, B, C
WHERE   B.idA = A.id AND 
        B.idC = C.id
GROUP   BY A.id, A.name

输出

╔════╦══════╦══════╗
║ id ║ name ║ Type ║
╠════╬══════╬══════╣
║  1 ║ Ann  ║ x,y  ║
║  2 ║ Bill ║ z    ║
║  3 ║ Mike ║ y    ║
║  4 ║ Zoey ║ x    ║
╚════╩══════╩══════╝

来自 SQLite 文档

The group_concat() function returns a string which is the concatenation of all non-NULL values of X. If parameter Y is present then it is used as the separator between instances of X. A comma (",") is used as the separator if Y is omitted. The order of the concatenated elements is arbitrary.

关于sql - 如何使用 sqlite 中的 View 在特定行中添加列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15859194/

相关文章:

iphone - 使用sqlite进行iPhone本地化?

mysql - 当从 MySQL 中的连接表中进行选择时,连接操作是否发生在选择之前?

python - 在 Django 购物车应用程序中实现 "Save For Later"功能?

php - 警告:mysqli::query():空查询

mysql - mySQL查询中两个变量中的较大者

php - EasyPHP 升级后 MySQL 密码被拒绝

SQLite INSERT SELECT 查询结果到现有表中?

django - django左联接查询

sql - Postgres 将时间戳列约束从 NOT NULL 更改为 NULL

php - PDO 使用键作为列名插入数组