sql - 使用 SQLite SELECT 使用连接表将连接表列合并为每个类别的一行

标签 sql sqlite select group-concat junction-table

我正在使用 SQLite 并且有三个表(这些表中有更多数据 - 此处缩写):

  • 类别 - 包含项目类别(id、名称、描述)
  • 项目 - (id, name, status)
  • 引用(id、cat_id、item_id)

类别可以有很多项目与之关联,也可以没有。 项目必须至少有 1 个类别,并且可以属于多个类别。

例子:

(Categories)
| id | name   | description                     |
|----|--------|---------------------------------|
| 1. | wet.   | something associated with water |
| 2. | dry.   | something else                  |
| 3. | metal. | steel, copper                   |
(Items)
| id. | name.   | status     |
|-----|---------|------------|
| 11. | river.  | north fork |
| 12. | lake.   | big        |
| 13. | river.  | south fork |
| 14. | desert. | mojave     |
| 15. | car.    | ford       |
| 16. | truck.  | chevy      |
(Reference)
| id | cat_id. | item_id |
|----|---------|---------|
| 21 | 1       | 11      |
| 22 | 1       | 12      |
| 23 | 2       | 14      |
| 24 | 3       | 15      |
| 25 | 3       | 16      |

使用以下内容:

SELECT c.name,(i.name || "-" || i.status) as Related from Items as i
join Categories c where c.id = cat.id

我得到的东西看起来像这样:

| c.name  | Related            |
|---------|--------------------|
| wet     | river - north fork |
| wet     | lake - big         |
| wet     | river - south fork |
| dry     | desert - mojave    |
| metal   | car - ford         |
| metal   | truck - chevy      |

我需要的是

| c.name | Related                                            |
|--------|----------------------------------------------------|
| wet    | river - north fork, lake - big, river - south fork |
| dry    | desert - mojave                                    |
| metal  | car - ford, truck - chevy                          |

一个类别与联结表中的引用项目匹配并组合在“相关”列中(示例中以逗号分隔)。

我如何在 SQLite 中得到这个结果?

最佳答案

您必须先将 Categories 连接到 Reference,然后再连接到 Items,使用 LEFT 连接,以防万一一个类别没有任何相关的项目,然后使用 GROUP_CONCAT() 聚合:

SELECT c.name,
       GROUP_CONCAT(i.name || ' - ' || i.status, ', ') Related
FROM Categories c
LEFT JOIN Reference r ON r.cat_id = c.id
LEFT JOIN Items i ON i.id = r.item_id
GROUP BY c.id, c.name

参见 demo .
结果:

| name  | Related                        |
| ----- | ------------------------------ |
| wet   | river - north fork, lake - big |
| dry   | desert - mojave                |
| metal | car - ford, truck - chevy      |

关于sql - 使用 SQLite SELECT 使用连接表将连接表列合并为每个类别的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65487615/

相关文章:

sql - 如何查找查询执行的次数?

mysql - 如果第一个结果为空,如何运行第二个 SQL 查询

sqlite - 二郎-sqlite3 sqlite3 :table_info error

django - 带有 SelectMultiple 小部件的 MultipleChoiceField "Value [...] not a valid choice."

PHP PDO mysql 按结果 ID 获取行

Mysql查询执行时间很长

java - 应用程序在 onTextChanged() 期间崩溃

sql - 为防止插入的sqlite数据库创建触发器

jquery - 在选择标签上使用 val(...) 时触发更改

php - 在单个数组中返回多个 SELECT 查询