开发者

MySQL - Join 2 Tables and Group Values

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
--------
compan开发者_运维百科yId (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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜