Andre Calenta
Andre Calenta

Reputation: 87

Select mysql rows where there exist 2 different values for same condition

I have the following dataset:

Table 1

first_value | second_value

same | 1

same | 2

different1 |1

different2 |2

What I'd like to obtain from this table is same because 'same' exists for both "1" and "2". different1 only exists for 1 and different2 only exists for 2, so they are not chosen... is this possible? Thank you very much for your help...

Upvotes: 0

Views: 622

Answers (2)

Marcel Burkhard
Marcel Burkhard

Reputation: 3523

Based on radar's answer and your comment that you're using php and already know the numbers:

$ids = array(1,2);//You probably already have an array holding your numbers

if(is_array($ids) && count($ids) >0) {

    $query = "SELECT col1 ".
             "FROM table1 ".
             "WHERE col2 IN (".join(",", $ids).") ".
             "GROUP BY col1 ".
             "HAVING COUNT(*) = ".count($ids);
}

If you're using parameterized queries it would of course look a little different.

Upvotes: 0

radar
radar

Reputation: 13425

you can use group by with having clause.

SELECT first_value
from Table1
where second_value in (1,2)
group by first_value
having count(*) =2

Upvotes: 2

Related Questions