I have a single table called employees
:
id | name | born | stinky
-------------------------------------------------
1 Chris 1982 1
2 Chris 1982 1
3 Bob 1982 0
4 Chris 1982 1
I want to grab rows 2, 4 based on the following condition:
SELECT
id,name,born,stinky
FROM
employees
WHERE
name=(SELECT name FROM employees WHERE id=1)
AND
born=(SELECT born FROM employees WHERE id=1)
AND
stinky=(SELECT stinky FROM employees WHERE id=1)
AND
id != 1
Is there a way to optimize this to only execute one single sub-query, and then reference the sub-query data multiple times? For example, something like this:
SELECT
id,name,born,stinky
FROM
employees
SUBQUERY
(SELECT name FROM employees WHERE id=1) AS XX
WHERE
name=XX.name
AND
born=XX.born
AND
stinky=XX.stinky
AND
id != 1
You can use the subquery only once:
SELECT id,name,born,stinky
FROM employees
WHERE (name,born,stinky) = (SELECT name,born,stinky FROM employees WHERE id=1)
AND id <> 1
Another way to do it is with a join:
SELECT e.id,e.name,e.born,e.stinky
FROM employees e
INNER JOIN (SELECT * FROM employees WHERE id=1) t
ON (t.name,t.born,t.stinky) = (e.name,e.born,e.stinky) AND t.id <> e.id
See the demo.
Results:
id | name | born | stinky |
---|---|---|---|
2 | Chris | 1982 | 1 |
4 | Chris | 1982 | 1 |