MySQL - Join 2 Tables and Group Values

拜拜、爱过 提交于 2021-02-08 08:16:05

问题


I've gotten some good help on here with some tricky stuff like this, so thought I'd have you guys take a look and see if this is even possible.

I have two tables in MySQL .. company and resources ...

companies can have multiple resources .. so ...

company
--------
companyId (primary/auto inc)
companyName

resources
---------
resourceId (primary/auto inc)
companyId
resourceName

I'd like to query the two tables and group it so the results look like this ...

Example...

Company Name
 ResourceName1
 ResourceName2
 ResourceName3
Company Name
 Resource Name4
 Resource Name5
Company Name3
 Resource Name6

etc..

Hope that makes sense.. any help is much appreciated.

Update

Ok to help clarify this a little better ...

I need to pull up every company in the company table, and then using that companyId, use that to pull every resource in the resource table with that same companyId ...

So the list would look like this ...

Bob's Plumbing (aka Company name)
  Bob the Plumber (has CompanyId of Bob's Plumbing)
  Bob's Assistant (has CompanyId of Bob's Plumbing)
Joe's Roofing (aka Company name)
  Joe the Roofer (has CompanyId of Joe's Roofing)

etc.. etc...

Hope that clears up some of the confusion.


回答1:


I could suggets this query -

EDITed

SELECT
  c.companyName,
  GROUP_CONCAT(CONCAT(r.resourceName, ' ', r.resourceFirstname, ' ', r.resourceLastname) SEPARATOR '\r\n')
FROM
  company c
JOIN
  resources r
    ON c.companyId = r.companyId
GROUP BY
  c.companyId;

Note, that company name and its resources will be in one row.




回答2:


select companyName,GROUP_CONCAT(resourceName) from company,resources where company.companyId=resources.companyId;


来源:https://stackoverflow.com/questions/6923038/mysql-join-2-tables-and-group-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!