使用 SQLite SELECT 将联接的 table 列合并为使用联结 table 的每个类别的一行

Use SQLite SELECT to combine joined table column into one row for each category using a junction table

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

类别可以有许多与之关联的项目或 none。 项目必须至少有 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                          |

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

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

您可以按如下方式使用group_concat

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

您可以这样写查询:

select c.name,
       group_concat(i.name || '-' || i.status, ', ') as Related
from Items i join
     Categories c 
     on c.id = i.cat_id
group by c.name;

备注:

  • JOIN 应始终使用 ON 作为 JOIN 条件。
  • SQL.
  • 中的字符串使用单引号
  • 默认分隔符是','。你似乎想要', ',所以你需要第二个参数。
  • 你需要GROUP BY.

您必须先将 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      |

forpas 的回复正是我所需要的。谢谢-

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