curved
curved

Reputation: 155

MySQL list queries equal to multiple values

I am trying to list people from California, Los Angeles who are male or female but I don't want all males and females from California to be listed.

SELECT * FROM people 
WHERE state='california' 
    AND city='los_angeles' 
    AND gender='male' OR gender='female'

I also tried:

SELECT * FROM people 
WHERE city='los_angeles' 
    AND gender='male' OR gender='female'

Upvotes: 0

Views: 79

Answers (2)

Axel Amthor
Axel Amthor

Reputation: 11106

More compact:

$sql = mysql_query("SELECT * FROM people WHERE state='california' 
               AND city='los_angeles' AND gender in ('male','female')");

Upvotes: 3

rtruszk
rtruszk

Reputation: 3922

When you combine AND and OR operators you have to remember that AND has higher precedence. So you have to use parenthesis:

$sql = mysql_query("SELECT * FROM people WHERE state='california' 
          AND city='los_angeles' AND (gender='male' OR gender='female')");

Your query returned all males from Los Angeles. It also returned all females (no matter from which city)

see this link for details about AND/OR operators
and this link for operator precedence

Upvotes: 2

Related Questions