[英]Complex SELECT MySQL statement
I have run into an issue selecting data from my MySQL database. 我从MySQL数据库中选择数据时遇到问题。
For example, I have a table with the following columns & tables: 例如,我有一个包含以下列和表的表:
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
...
I want to get the amount
from all the rows that match the food
type of a selected id
. 我想从与所选
id
的food
类型匹配的所有行中获取amount
。
Eg If I choose id: 102
then it would get the amount
from ALL rows where the food = 'Everything'
例如,如果我选择
id: 102
那么它将从food = 'Everything'
所有行中获取amount
SELECT amount FROM farming WHERE food = '".$_GET['food']."' **IS THE SAME TYPE AS IT IS IN** id = '1'";
// This should select 10
, 19
and 3
from amount
(as id = 1
's foodtype is Grass
, so it should select amount
from all rows where foodtype = grass. SELECT amount FROM farming WHERE food = '".$_GET['food']."' **IS THE SAME TYPE AS IT IS IN** id = '1'";
//这应该选择10
, 19
和3
从amount
(因为id = 1
的食物类型是Grass
,因此它应从所有食物类型=草的行中选择amount
。
** is where I'm facing issues, I've tried various statements and can't seem to get it to work. **是我面临的问题,我尝试了各种声明,但似乎无法使其正常工作。
You could use group by clause which will sum up all value from amount column whre food = 'Grass' 您可以使用group by子句,该子句将从数量列中的所有值求和,即food ='Grass'
SELECT SUM(amount) ammount FROM farming
WHERE food = (select food FROM farming where id = 102)
GROUP BY food
This should do the trick 这应该可以解决问题
select amount
from farming
where food = (
select food
from farming
where id = 1
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.