简体   繁体   中英

PostgreSQL - WHERE condition which refers to 2 different records and should be TRUE

I have tables:

company_employees:

id_employee
id_company

employees:

id_employee
name

companies:

id_company
name

If I execute such as query:

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

It displays:

+-----------+--------------+
|  Company  |   Employee   |
+-----------+--------------+
| Microsoft | John Smith   |
| Microsoft | Mike Brown   |
| IBM       | Chris Miller |
+-----------+--------------+

I want to display only company names ( companies.name) where work employees both 'John Smith' and 'Mike Brown'. So the query should display:

+-----------+
|   name    |
+-----------+
| Microsoft |
+-----------+

Do you have any idea how to do that? Thanks!

We can try aggregating by company name, and then asserting that:

  • The only two names in each company group are 'John Smith' and 'Mike Brown'
  • The number of distinct names in each company group is two

Both of these conditions would imply that any company in the result set matches your criteria.

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);

you can try like below if 2different employee work on same company below will work

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

DEMO in fiddle

company
Microsoft

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM