我在 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/