0

Is it possible to make the code below work. At the moment it only show employees from "New York" but not employees from "Chicago".?

SELECT employees.ename, zipcodes.city
FROM employees
LEFT JOIN zipcodes
ON employees.zip=zipcodes.zip
WHERE employees.zip =
(
SELECT zipcodes.zip
FROM zipcodes
WHERE zipcodes.city = 'New York' OR 'Chicago'
)
ORDER BY employees.eno;

Thanks in advance!

//René

1 Answer 1

1

Use the IN condition, like this:

SELECT employees.ename, zipcodes.city
FROM employees
LEFT JOIN zipcodes
ON employees.zip=zipcodes.zip
WHERE employees.zip IN
(
    SELECT zipcodes.zip
    FROM zipcodes
    WHERE zipcodes.city IN ('New York', 'Chicago')
)
ORDER BY employees.eno

Another approach (possibly better one) is to use the JOIN condition itself instead of a sub query, like this:

SELECT employees.ename, zipcodes.city
FROM employees
LEFT JOIN zipcodes
ON employees.zip=zipcodes.zip
AND zipcodes.city IN ('New York', 'Chicago')
ORDER BY employees.eno
Sign up to request clarification or add additional context in comments.

7 Comments

It still just show the first result "New York" and does not take "Chicago" into account. Am I still missing something? Is there a better way to show employees that live in "New York" or "Chicago"?
@VanDerPrygel Usage of OR should be like this WHERE zipcodes.city = 'New York' OR zipcodes.city = 'Chicago'. Alternatively use the IN condition in the WHERE clause as well. I have updated my answer above.
I missed that you had changed the "OR" with an ",". Now it works.
But why do it this way? Does it offer some advantage over a regular join?
@Strawberry good thought. Not sure about any performance gain, however using second JOIN condition (instead of subquery) seems a better approach.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.