sql-如何从中间表中获取单味配方

lndjwyie  于 2021-06-25  发布在  Mysql
关注(0)|答案(4)|浏览(365)

正如你在下表中看到的,有些食谱有2种或更多的口味,但有些只有1种。我想拿回一张table,上面有单味食谱的香精id和香精量。我设法得到了一些信息,但我不能太多的味道。。我最接近的就是这个问题

SELECT COUNT('flavor_id') as flavors, `recipe_id`, 
MAX(flavor_id) as flavor_id 
FROM `flavor_recipe` 
GROUP BY `recipe_id` 
HAVING flavors = 1;

但还是什么都没有。需要帮忙吗?谢谢您。

ve7v8dk2

ve7v8dk21#

你可以做广告 concat 最大值和最小值。但只有您才能在同一列中看到两个ID。

SELECT COUNT('flavor_id') as flavors, `recipe_id`, CONCAT(MIN(flavor_id), MAX(flavor_id)) as flavor_id FROM `flavor_recipe` GROUP BY `recipe_id` HAVING flavors = 1;
ssm49v7z

ssm49v7z2#

戈登的回答让我想起了那些子问题。所以我想试一试,找到了解决办法

SELECT `*`
FROM `flavor_recipe`
WHERE `recipe_id` IN 
   (SELECT `recipe_id` FROM `flavor_recipe` 
   GROUP BY `recipe_id` 
   HAVING COUNT(flavor_id) = 1);

很简单,我不敢相信我之前没有想到子查询。。谢谢

stszievb

stszievb3#

当你有 ONLY_FULL_GROUP_BY 如果启用了sql模式,则可以使用 ANY_VALUE() 功能。

SELECT recipe_id, COUNT(*) AS flavors, ANY_VALUE(flavor_id) AS flavor_id
FROM flavor_recipe
GROUP BY recipe_id
HAVING flavors = 1
7ivaypg9

7ivaypg94#

这可能更有效:

select fr.*
from flavor_recipe fr
where not exists (select 1
                  from flavor_recipe fr2
                  where fr2.recipe_id = fr.recipe_id and fr2.flavor_id <> fr.flavor_id
                 );

特别是,您需要一个索引 flavor_recipe(recipe_id, flavor_id) .

相关问题