简体   繁体   English

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

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

I have the following dataset: 我有以下数据集:

Table 1 表格1

first_value | first_value | second_value second_value

same | 一样 1 1个

same | 一样 2 2

different1 |1 不同的1 | 1

different2 |2 不同的2 | 2

What I'd like to obtain from this table is same because 'same' exists for both "1" and "2". 我想从该表中获取的内容是相同的,因为“ 1”和“ 2”都存在“相同”。 different1 only exists for 1 and different2 only exists for 2, so they are not chosen... is this possible? different1仅针对1存在, different2仅针对2存在,因此未选择它们……这可能吗? Thank you very much for your help... 非常感谢您的帮助...

you can use group by with having clause. 您可以group by具有having子句使用group by

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

Based on radar's answer and your comment that you're using php and already know the numbers: 根据雷达的答案和您使用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);
}

If you're using parameterized queries it would of course look a little different. 如果您使用的是参数化查询,那看起来当然会有些不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM