使用四个表查询SQL

时间:2014-05-23 13:38:28

标签: mysql sql database

有人可以解释一下如何查询这些表格,以获得他们所在的每个国家的公司员工人数吗?结果列的数量应为3,公司,国家和员工。公司和分公司已连接但国家与城市相连,因此我不确定如何解决这个问题。谢谢你们,欣赏它!!!

CREATE TABLE country (
  id         integer NOT NULL PRIMARY KEY,
  name       varchar NOT NULL,
  population integer check(population > 0)
);

CREATE TABLE city (
  id         integer NOT NULL PRIMARY KEY,
  name       varchar NOT NULL,
  population integer check(population > 0),
  country    integer NOT NULL REFERENCES country(id)
);

CREATE TABLE company (
  id         integer NOT NULL PRIMARY KEY,
  name       varchar NOT NULL
);

CREATE TABLE branch (
  company    integer NOT NULL REFERENCES company(id),
  city       integer NOT NULL REFERENCES city(id),
  name       varchar,
  employees  integer NOT NULL,
  PRIMARY KEY (company, city)
);

这就是我所做的,但我知道这是错误的,我尝试了我的组合,但到目前为止没有什么是正确的!

SELECT 
branch.employees,
company.name AS company,
country.name AS country

FROM branch

INNER JOIN company 
ON branch.company = company.id

INNER JOIN country
ON city.country = country.id
ORDER BY country;

1 个答案:

答案 0 :(得分:0)

SELECT
  company.name AS company,
  country.name AS country, 
  sum(branch.employees) AS country_employees
FROM branch
JOIN company ON company.id = branch.company
JOIN city ON city.id = branch.city
JOIN country ON country.id = city.country
GROUP BY company.name, country.name
ORDER BY country.name, company.name;

您希望总结每个公司的员工数量,对于他们所在的每个国家/地区。这意味着当GROUP BY每个分支的员工数量SUM时,您必须{{1}}这两个字段。您也需要使用城市表,即使您没有显示任何数据。

阅读汇总函数以获取更多背景信息。