2012-03-29 47 views
0

獲取相同的ID我有我的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表有很多條目。此表顯示配方中使用的成分。

現在我想找到包含了像粉和糖incredients配方:

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 

這statment是錯誤的,因爲在Recipe_Pos一個條目不能同時包含incredients。

什麼是正確的查詢?它應該只用1個便宜和更多

回答

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