简体   繁体   中英

using basic join for sql query for multiple values

hoping someone can help, I've used search but answers are beyond what we aare covering.

I'm looking to pull up "staff member who looks after property in Glasgow or Aberdeen" using the below code:

SELECT s.fName, s.lName, propertyNo
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo 
AND city = 'Glasgow' OR 'Aberdeen';

only Glasgow is being returned ..I've also tried AND which returns nothing. I'm completely new to this so I know I'm missing something very basic.

SELECT s.fName, s.lName, propertyNo
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo 
AND (city = 'Glasgow' OR city='Aberdeen');

This can also be rewritten to

SELECT s.fName, s.lName, propertyNo
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo 
AND city in('Glasgow', 'Aberdeen');

However, you should use a proper join structure to let the optimizer do its thing

SELECT s.fName, s.lName, propertyNo
FROM Staff s 
INNER JOIN PropertyForRent p ON s.staffNo = p.staffNo 
WHERE (city = 'Glasgow' OR city='Aberdeen');

You have missed the brackets it should be

a AND (b OR c)

Edit and after the OR you have to write city = x again. And you should prefix all of your fields like you do it with s.fName . p.propertyNo and city should also be prefixed.

It's better to use explicit JOINs.

SELECT s.fName, s.lName, propertyNo
FROM Staff AS s
INNER JOIN PropertyForRent AS p
ON s.staffNo = p.staffNo 
AND city IN ('Glasgow', 'Aberdeen')

In SQL, you should give the field name before value same like in many programming languages.

SELECT s.fName, s.lName, propertyNo
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo 
AND (p.city = 'Glasgow' OR p.city='Aberdeen');

Have you tried :

city in ('Glasgow', 'Aberdeen');

or

city = 'Glasgow' or city = 'Aberdeen'

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