postgreSQL:JOIN和GROUP BY以获得正确的查询结果

时间:2018-06-12 00:31:37

标签: arrays postgresql join group-by

我是一名postgreSQL新手,我被困在以下查询中。

理想的输出是

id |   name      | address | description | employees
1  |  'company1' | 'asdf'  |  'asdf'     | [{id: 1, name: 'Mark'}, {id: 2, name: 'Mark'}, {id: 3, name: 'Steve'}, {id: 4, name: 'Mark'}]
2 ...
3 ...
5  |  'company5' | 'asdf   | 'adsf'      | []

我当前的查询(不起作用)

SELECT companies.* ,employees.*,json_agg(companies_employees.*) as "item"
FROM
  companies_employees
  JOIN companies ON companies_employees.COMPANY_id = companies.ID 
  JOIN employees ON companies_employees.EMPLOYEE_id = employees.ID
GROUP BY companies.ID, companies.NAME, companies.ADDRESS,companies.DESCRIPTION,employees.ID, employees.NAME

共有3个表格:

companies : ID, NAME, ADDRESS, DESCRIPTION
employees : ID, NAME, SALARY, ROLE
companies_employees : EMPLOYEE_ID, COMPANY_ID 
(CONSTRAINT companies_employees_employee_fkey FOREIGN KEY(employee_id) REFERENCES employees(id),
CONSTRAINT companies_employees_company_fkey FOREIGN KEY(company_id) REFERENCES companies(id) ) 

示例表为[http://sqlfiddle.com/#!15/27982/29][here]

也许“GROUP BY”不适合使用。

请你引导我走向正确的方向吗? 非常感谢提前

1 个答案:

答案 0 :(得分:0)

http://sqlfiddle.com/#!15/8849a/1

您的问题是您正在显示员工数据并按条件在您的组中使用该数据。这些字段具有唯一值。您只想对公司信息进行分组:

SELECT
  companies.*,json_agg(employees.*) as "employees"
FROM
  companies_employees
  JOIN companies ON companies_employees.COMPANY_id = companies.ID
  JOIN employees ON companies_employees.EMPLOYEE_id = employees.ID
GROUP BY 
  companies.ID, 
  companies.NAME, 
  companies.ADDRESS,
  companies.DESCRIPTION