Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL SELECT query with multiple conditions
    primarykey
    data
    text
    <p>I'm stuck with a SQL query. Let's say we have an employee, a task table and a many to many association between them. The tables look like this:</p> <pre><code>employees id|name 1 | John 2 | Peter 3 | Mike tasks id | name 1 | Support 2 | Programming 3 | Call customers 4 | Write Newsletters 5 | Write Invoices employees_tasks employee_id | task_id 1 | 1 1 | 2 2 | 3 2 | 4 2 | 5 3 | 2 </code></pre> <p>Now I want to get all employees, who have "Programming" as their tasks. The correct query is:</p> <pre><code>SELECT employees.id, employees.name FROM employees INNER JOIN employees_tasks ON employees.id = employees_tasks.employee_id INNER JOIN tasks ON employees_tasks.task_id = tasks.id WHERE tasks.name LIKE 'Programming' </code></pre> <p>So far so good... But now I want to get all employees, whose tasks are "Programming" <em>and</em> "Support". This query gives me NULL:</p> <pre><code>SELECT employees.id, employees.name FROM employees INNER JOIN employees_tasks ON employees.id = employees_tasks.employee_id INNER JOIN tasks ON employees_tasks.task_id = tasks.id WHERE tasks.name LIKE 'Programming' AND tasks.name LIKE 'Support' </code></pre> <p>I receive three records with this query</p> <pre><code>SELECT employees.id, employees.name FROM employees INNER JOIN employees_tasks ON employees.id = employees_tasks.employee_id INNER JOIN tasks ON employees_tasks.task_id = tasks.id WHERE tasks.name IN ('Programming', 'Support') </code></pre> <p>2x John and 1x Mike. But that's not what I want. I want all employees, who have the tasks "Programming" AND "Support" - not those, who only have one of the tasks.</p> <p>There's another option. I use ALL with a subquery. Here we go:</p> <pre><code>SELECT employees.id, employees.name FROM employees INNER JOIN employees_tasks ON employees.id = employees_tasks.employee_id INNER JOIN tasks ON employees_tasks.task_id = tasks.id WHERE tasks.name = ALL (SELECT DISTINCT name FROM tasks WHERE name LIKE 'Programming' OR name LIKE 'Support') </code></pre> <p>But I receive with this query NULL, although there is an employee, who have both tasks: John!</p> <p>How can I implement such a query?</p> <p>Best Regards Christian</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload