I have 3 tables called:
- Applications (id, name)
- Resources (id, name)
- ApplicationsResources (id, app_id, resource_id)
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.
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?
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?
MySQL
SQL Server (2005+)
SQL Server (2017+)
Oracle
I recommend reading about string aggregation/concatentation in Oracle.
There is no way to do it in a DB-agnostic way. So you need to get the whole data-set like this:
And then concat the AppName programmatically while grouping by ResName.
I believe what you want is:
SELECT ItemName, GROUP_CONCAT(DepartmentId) FROM table_name GROUP BY ItemName
If you're using MySQL
Reference
I don't know if there's any solution to do this in a database-agnostic way, since you most likely will need some form of string manipulation, and those are typically different between vendors.
For SQL Server 2005 and up, you could use:
It uses the SQL Server 2005
FOR XML PATH
construct to list the subitems (the applications for a given resource) as a comma-separated list.Marc
I think we could write in the following way to retrieve(below code is just an example, please modify as needed):
This will do it in SQL Server: