How do I create a comma-separated list using a SQL query?(如何使用 SQL 查询创建逗号分隔的列表?)
问题描述
我有 3 个表:
- 应用程序(ID、名称)
- 资源(id、名称)
- 应用程序资源(id、app_id、resource_id)
我想在 GUI 上显示所有资源名称的表格.在每一行的一个单元格中,我想列出该资源的所有应用程序(逗号分隔).
I want to show on a GUI a table of all resource names. In one cell in each row I would like to list out all of the applications (comma separated) of that resource.
所以问题是,在 SQL 中执行此操作的最佳方法是什么,因为我需要获取所有资源,并且还需要获取每个资源的所有应用程序?
So the question is, what is the best way to do this in SQL as I need to get all resources and I also need to get all applications for each resource?
我是否首先从资源中运行 select *,然后遍历每个资源并对每个资源执行单独的查询以获取该资源的应用程序列表?
Do I run a select * from resources first and then loop through each resource and do a separate query per resource to get the list of applications for that resource?
有没有办法在一个查询中做到这一点?
Is there a way I can do this in one query?
推荐答案
没有办法以与数据库无关的方式来做到这一点.所以你需要像这样获取整个数据集:
There is no way to do it in a DB-agnostic way. So you need to get the whole data-set like this:
select
r.name as ResName,
a.name as AppName
from
Resouces as r,
Applications as a,
ApplicationsResources as ar
where
ar.app_id = a.id
and ar.resource_id = r.id
然后在按 ResName 分组的同时以编程方式连接 AppName.
And then concat the AppName programmatically while grouping by ResName.
这篇关于如何使用 SQL 查询创建逗号分隔的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 SQL 查询创建逗号分隔的列表?


基础教程推荐
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01