选择具有给定 ID 的所有行,如果其中至少一行具有给定值


SELECT all rows with a given ID if at least one of those rows has a given value

我有一个mySQL查询,它将选择一些饮料并返回有关饮料的基本信息,以及该特定饮料的成分列表,以及特定饮料的评级。我有3桌饮料,drinks_ratings,drinks_ing

所以,我的问题是,假设我想获取有关含有伏特加的饮料的信息,并且放在高球杯中,我会运行下面的查询......

有效,只是我的问题是它不会将所有成分返回。例如,如果我返回"randomDrinkName1",它恰好有伏特加和苏打水......当我得到信息时,它省略了苏打水,因为我说 WHERE ing = voda,所以我明白为什么会发生这种情况......但是我是否可以做其他类型的 WHERE 子句来检查它是否有"伏特加"并将其与可能也存在的所有其他成分信息一起返回?

我知道我可以在此查询之前进行查询,该查询从我的drinks_ing表中获取包含伏特加的返回 ID。

但这似乎可能是个坏主意...就像如果有 1000 种含有伏特加的饮料只是为了对带有 1000 OR 语句的选择进行查询。

我很感兴趣是否有一种方法可以在一个查询中轻松完成所有这些操作。 谢谢!

select dIngs.id,
    dIngs.name,
    dIngs.descrip,
    dIngs.type,
    dIngs.ing,
    AVG(b.rating) as arating,
    COUNT(b.id) as tvotes
from (
    select a.id,
        a.name,
        a.descrip,
        a.type,
        concat (
            '[',
            GROUP_CONCAT('{'"ing'":', c.ing, ','"parts'":', c.parts, '}'),
            ']'
            ) ing
    from drinks a
    left join drinks_ing c on a.id = c.did
    where c.ing = "vodka"
        and a.type = "highball"
    group by a.id
    ) dIngs
left join drinks_ratings b on dIngs.id = b.id
group by dIngs.id
order by arating desc,
    tvotes desc LIMIT 0,
    50;

编辑:为了说明我想要得到的结果是这样的:

           [0]
              descrip = "the description text will be here"
              arating = 0
              id = 4
              ing = [ {"ing": "vodka", "parts": 4}, {"ing": "soda", "parts": 2}, {"ing": "sprite", "parts": 2} ]
              name = "awesomeDrink"
              type = "highball"
              tvotes = 0

但我实际上得到的只是伏特加,因为这就是我正在检查的

           [0]
              descrip = "the description text will be here"
              arating = 0
              id = 4
              ing = [ {"ing": "vodka", "parts": 4} ]
              name = "awesomeDrink"
              type = "highball"
              tvotes = 0

需要明确的是,如果我不提供像where ing = vodka这样的东西,我会把所有的成分都拿回来。 这不是问题所在。

我需要它来检查潜在成分之一是否恰好是伏特加,然后基本上返回所有 ing 数据......如果伏特加不是潜在的成分,请忽略该饮料,不要退货。

编辑:我的桌子是什么样子的..

drinks_ing
---------------
did (which is the drink id its associated with)
id (the id of the ingredient aka "vodka")
parts
drinks
---------------
id
name
description
type
timestamp
drinks_ratings
-----------------
id
userid
rating
timestamp

最好的方法可能是使用自联接。 这是两次引用同一表的地方,但使用不同的名称。 大致如下所示:

SELECT     d.stuff
FROM       drinks d
INNER JOIN drinks v on d.id = v.id
WHERE      v.ingredient = "vodka"

更新:使其更好地对应于有问题的表格。 这是说:给定所有伏特加成分,找到与伏特加成分相同的饮料中的所有成分。

SELECT     d.*
FROM       drinks_ing d
INNER JOIN drinks_ing v on d.did = v.did
WHERE      v.ing = "vodka"

是的,您可以在一个查询中完成。 您的旅馆

SELECT a.id, a.name, a.descrip, a.type, CONCAT('[', GROUP_CONCAT('{'"ing'":', c.ing, ','"parts'":', c.parts, '}'), ']') ing
FROM drinks a LEFT JOIN drinks_ing c
     ON a.id = c.did
WHERE a.id in (select distinct a.id
                from drinks_ing c
                     ON a.id = c.did
                where c.ing = "vodka"
               )

这将查找具有所需成分的饮料并返回有关饮料的信息。