一对多关系,选择值

时间:2015-06-07 18:25:24

标签: mysql sql

我有两张桌子?

**object**
object_id|name
1| one
2| two
3| three

**colors**
object_id|color_name
1| red
1| white
2| red
3| white

如何选择所有object_id,其中color_name等于红色 AND 白色,而不是红色或白色, 像这样

 `Select object_id 
  From colors 
  WHERE color_name='red' AND color_name='white'` 

但它废话..

1 个答案:

答案 0 :(得分:1)

使用GROUP BY子句尝试以下内容:

select object_id
from colors
where color_name in ('red','white')
group by object_id
having count(distinct color_name) >= 2

然后,如果您愿意,可以使用JOIN表格object此结果集

select o.object_id, o.name
from object o join (
    select object_id
    from colors
    where color_name in ('red','white')
    group by object_id
    having count(distinct color_name) >= 2
) tab on o.object_id = tab.object_id