复杂的SELECT MySQL语句

时间:2017-03-13 16:42:09

标签: php mysql

我遇到了从MySQL数据库中选择数据的问题。

例如,我有一个包含以下列的表格&表:

Table name: farming

id | animal | amount | food
----------------------------
1  |   Cow  |    10  | Grass
12 |  Sheep |    19  | Grass
23 |  Lion  |     1  | Everything
29 |  Lamb  |     3  | Grass
102|   Pig  |     8  | Everything
...

我希望从与所选amount的{​​{1}}类型相匹配的所有行中获取food

E.g。如果我选择id,则会从id: 102

的所有行中获得amount

food = 'Everything' //这应该从SELECT amount FROM farming WHERE food = '".$_GET['food']."' **IS THE SAME TYPE AS IT IS IN** id = '1'";中选择10193(因为amount的食物类型是{{1}所以它应该从foodtype = grass的所有行中选择id = 1

**是我遇到问题的地方,我尝试了各种各样的陈述,似乎无法让它发挥作用。

2 个答案:

答案 0 :(得分:0)

你可以使用group by子句来汇总所有来自金额列的食物值=' Grass'

SELECT SUM(amount) ammount FROM farming 
      WHERE food = (select food FROM farming where id = 102) 
      GROUP BY food

答案 1 :(得分:0)

这应该可以解决问题

select  amount
from    farming
where   food = (
            select  food
            from    farming
            where   id = 1
        )