PostgreSQL - WHERE 条件指的是 2 个不同的记录并且应该是 TRUE
PostgreSQL - WHERE condition which refers to 2 different records and should be TRUE
我有表:
company_employees:
id_employee
id_company
员工:
id_employee
name
公司:
id_company
name
如果我执行这样的查询:
SELECT companies.name AS Company, employees.name AS Employee FROM employees
INNER JOIN company_employees ON company_employees.id_employee = employees.id_employee
INNER JOIN companies ON companies.id_company = company_employees.id_company
显示:
+-----------+--------------+
| Company | Employee |
+-----------+--------------+
| Microsoft | John Smith |
| Microsoft | Mike Brown |
| IBM | Chris Miller |
+-----------+--------------+
我只想显示公司名称 (companies.name),其中员工 'John Smith' 和 'Mike Brown'。所以查询应该显示:
+-----------+
| name |
+-----------+
| Microsoft |
+-----------+
你知道怎么做吗?谢谢!
我们可以尝试按公司名称聚合,然后断言:
- 每个公司组中仅有的两个名字是'John Smith'和'Mike Brown'
- 每个公司组中不同名称的数量是两个
这两个条件都意味着结果集中的任何公司都符合您的条件。
SELECT
c.name AS Company
FROM employees e
INNER JOIN company_employees ce
ON ce.id_employee = ee.id_employee
INNER JOIN companies c
ON c.id_company = ce.id_company
WHERE
e.name IN ('John Smith', 'Mike Brown')
GROUP BY
c.name
HAVING
MIN(e.name) <> MAX(e.name);
如果 2 个不同的员工在下面的同一家公司工作,您可以像下面这样尝试
SELECT
c.name AS Company
FROM employees e
INNER JOIN company_employees ce
ON ce.id_employee = e.id_employee
INNER JOIN companies c
ON c.id_company = ce.id_company
GROUP BY
c.name
HAVING
count(distinct e.name)=2
company
Microsoft
我有表:
company_employees:
id_employee
id_company
员工:
id_employee
name
公司:
id_company
name
如果我执行这样的查询:
SELECT companies.name AS Company, employees.name AS Employee FROM employees
INNER JOIN company_employees ON company_employees.id_employee = employees.id_employee
INNER JOIN companies ON companies.id_company = company_employees.id_company
显示:
+-----------+--------------+
| Company | Employee |
+-----------+--------------+
| Microsoft | John Smith |
| Microsoft | Mike Brown |
| IBM | Chris Miller |
+-----------+--------------+
我只想显示公司名称 (companies.name),其中员工 'John Smith' 和 'Mike Brown'。所以查询应该显示:
+-----------+
| name |
+-----------+
| Microsoft |
+-----------+
你知道怎么做吗?谢谢!
我们可以尝试按公司名称聚合,然后断言:
- 每个公司组中仅有的两个名字是'John Smith'和'Mike Brown'
- 每个公司组中不同名称的数量是两个
这两个条件都意味着结果集中的任何公司都符合您的条件。
SELECT
c.name AS Company
FROM employees e
INNER JOIN company_employees ce
ON ce.id_employee = ee.id_employee
INNER JOIN companies c
ON c.id_company = ce.id_company
WHERE
e.name IN ('John Smith', 'Mike Brown')
GROUP BY
c.name
HAVING
MIN(e.name) <> MAX(e.name);
如果 2 个不同的员工在下面的同一家公司工作,您可以像下面这样尝试
SELECT
c.name AS Company
FROM employees e
INNER JOIN company_employees ce
ON ce.id_employee = e.id_employee
INNER JOIN companies c
ON c.id_company = ce.id_company
GROUP BY
c.name
HAVING
count(distinct e.name)=2
company
Microsoft