我在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 |
+-----+-------+-------+
不重复任何一行,这是可能的吗?
答案 0 :(得分: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,则用作分隔符。的顺序 连接元素是任意的。
答案 1 :(得分: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文档