从详细信息表中获取相同的ID

时间:2012-03-29 17:41:31

标签: mysql

我的mysql数据库中有2个表:

CREATE TABLE IF NOT EXISTS `RECIPES` (
  `recipes_id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(50) COLLATE utf8_bin NOT NULL,
  `text` varchar(2000) COLLATE utf8_bin NOT NULL,
  `count_persons` int(11) NOT NULL,
  `duration` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `date` datetime NOT NULL,
  `accepted` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`recipes_id`),
  KEY `recipes_user_fk` (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=88 ;

CREATE TABLE IF NOT EXISTS `RECIPES_POS` (
  `recipes_pos_id` int(11) NOT NULL AUTO_INCREMENT,
  `recipes_id` int(11) NOT NULL,
  `ingredients_id` int(11) NOT NULL,
  `ingredients_value` int(11) NOT NULL,
  PRIMARY KEY (`recipes_pos_id`),
  KEY `recipe_pos_rec_id` (`recipes_id`),
  KEY `recipes_pos_ingredient_fk` (`ingredients_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=58 ;

在Recipe_Pos表中有很多条目。此表显示配方中使用的成分。

现在我想找到含有粉末和糖等令人难以置信的食谱:

SELECT r.recipes_id FROM RECIPES r, RECIPES_POS rp WHERE r.recipes_id = rp.recipes_id AND rp.ingredients_id =6 AND rp.ingredients_id =4

这个陈述是错误的,因为Recipe_Pos中的条目不能同时包含两个令人难以置信的内容。

什么是正确的查询?它应该只适用于1个令人难以置信的更多

1 个答案:

答案 0 :(得分:1)

select r.recipes_id
from RECIPES r
inner join RECIPES_POS rp on r.recipes_id = rp.recipes_id
where rp.ingredients_id in (4, 6)
group by r.recipes_id
having count(distinct rp.ingredients_id) = 2