Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple conditions on the same column in the WHERE clause

I have a table something like this -

RecordID   PropertyID       PropertyVal
--------------------------------------------------
3215            7           john doe
3215            11          Chicago
3215            13          Business Development Analyst
3216            7           jane doe
3216            11          Chicago
3216            13          Managing Director
3217            7           mike smith
3217            11          Chicago
3217            13          Business Development Analyst
3218            7           john smith
3218            11          Seattle
3218            13          Managing Director

How do I return the names of users where PropertyID = 13 AND PropertyVal='Business Development Analyst'AND PropertyID = 11 AND PropertyVal = 'Chicago'. How do I do multiple where clauses for the same column?

Edit: I need the result set to look like this -

Name
----
John Doe
Mike Smith
like image 744
tempid Avatar asked Nov 14 '12 19:11

tempid


People also ask

Can we use multiple conditions in WHERE clause?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition.

Can we use multiple values in WHERE clause in SQL?

The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.

WHERE multiple conditions add?

You can use the AND condition in the WHERE clause to specify more than 1 condition that must be met for the record to be selected.

Can we use multiple columns in WHERE clause?

If you want compare two or more columns. you must write a compound WHERE clause using logical operators Multiple-column subqueries enable you to combine duplicate WHERE conditions into a single WHERE clause.


3 Answers

select PropertyVal
from your_table
where PropertyID = 7
and RecordID in 
(
  select RecordID   
  from your_table
  where (PropertyID = 13 AND PropertyVal='Business Development Analyst')
     or (PropertyID = 11 AND PropertyVal = 'Chicago')
  group by RecordID   
  having count(distinct PropertyID) = 2
)
like image 103
juergen d Avatar answered Oct 14 '22 16:10

juergen d


Not sure what you want exactly. It's probably either

...
where (PropertyID = 13 AND PropertyVal='Business Development Analyst')
   or (PropertyID = 11 AND PropertyVal = 'Chicago')

or

...
where PropertyID in (13, 11) 
and PropertyVal in ('Business Development Analyst', 'Chicago')
like image 24
Bohemian Avatar answered Oct 14 '22 15:10

Bohemian


We can go with JOIN Clause...

Ex:

 SELECT LIST_OF_COLUMNS FROM TBL1 T1 JOIN TBL2 T2
    ON T1.COL1=T2.COL1 AND 
    T1.COL2=T2.COL2 AND 
    T1.COL3=T2.COL3 AND 
    T1.COL4=T2.COL4 
like image 27
Arief Avatar answered Oct 14 '22 15:10

Arief