开发者

How to group employees by their firms in MYSQL

I have two tables: Firms and Employees

I need a query so that all the Firm records are pulled, and within that query, pull the Employees for each firm.

For example:

ABC Company
Smith, John
Johnson, Tim

DEF Inc.
Jones, Mack
Frank, Tom

I have tried variations of JOIN, UNION, etc. with no luck开发者_如何学运维....


SELECT f.FirmName, GROUP_CONCAT(e.EmpName) AS Employees 
FROM Firm f LEFT JOIN Employee e on f.FirmID = e.FirmID
GROUP BY f.FirmID


A query like the below will give you a listing of all firms, and the LEFT JOIN includes companies even if it does not have any employees.

select f.name firmname, e.name
from firms f
left join employees e on e.firm_id = f.firm_id
order by firmname, e.name

From your front end display code, step through the records and whenever the firm name changes, start a new firm section.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜