1

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

表 A


+-----+-------+ | id | name | +-----+-------+ | 1 | Ann | | 2 | Bill | | 3 | Mike | | 4 | Zoey | +-----+-------+

表 B

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

表 C

+-----+-----+
|  id | type|
+-----+-----+
| 1   | x   |
| 2   | y   |
| 3   | z   |
+-----+-----+

我试过了:

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     |
+-----+-------+-------+

没有重复任何行,这可能吗?

4

2 回答 2

1

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 文档

group_concat()函数返回一个字符串,它是 X 的所有非 NULL 值的串联。如果存在参数 Y,则它用作 X 实例之间的分隔符。如果 Y 是,则使用逗号 (",") 作为分隔符省略。连接元素的顺序是任意的。

于 2013-04-07T05:31:59.790 回答
0

在定义视图时尝试这个查询:

SELECT A.id, A.name, GROUP_CONCAT(C.type) type
FROM A
INNER JOIN B ON B.idA = A.id
INNER JOIN C ON C.id = B.idC
GROUP BY A.id

查看 MySQL 文档GROUP_CONCAT()

于 2013-04-07T05:29:50.430 回答