MySQL通过引用一个数据字段来选择多行

时间:2012-11-06 11:19:30

标签: mysql sql select group-by having

===========================
= id = model_id = property =
===========================
= 14 = 1        = 1       =
===========================
= 15 = 1        = 3       =
===========================
= 16 = 2        = 1       =

我有一个像上面这样的表,我想只选择model_ids,其中property等于1 AND 3

如果你能告诉我如何

,我会很高兴

4 个答案:

答案 0 :(得分:2)

听起来你想要这个:

select model_id
from yourtable
where property in (1, 3)
group by model_id
having count(*) > 1;

请参阅SQL Fiddle with Demo

或者您可以使用以下内容:

select model_id
from yourtable t1
where property = 1
  and exists (select model_id
              from yourtable t2
              where t1.model_id = t2.model_id
                and property = 3)

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

您可以使用IN子句:

SELECT `model_id`
  FROM `table`
  WHERE `property` IN (1, 3)

答案 2 :(得分:0)

select model_ids from yourtable where property in(1,3)

答案 3 :(得分:0)

试试这个:

SELECT DISTINCT model_ids 
FROM tableName 
WHERE property in (1,3) 
GROUP BY model_ids 
HAVING COUNT( DISTINCT property ) = 2