选择相同条件存在2个不同值的mysql行

时间:2015-01-12 20:04:21

标签: mysql sql select

我有以下数据集:

表1

first_value | SECOND_VALUE

相同| 1

相同| 2

different1 | 1

different2 | 2

我希望从此表中获得相同,因为'相同'存在于" 1"和" 2"。 different1 仅存在1,而 different2 仅存在于2,因此不会选择它们......这可能吗?非常感谢你的帮助...

2 个答案:

答案 0 :(得分:2)

您可以将group byhaving子句一起使用。

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

答案 1 :(得分:0)

基于雷达的回答以及您使用php并且已经知道数字的评论:

$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);
}

如果您使用参数化查询,它当然会有所不同。