我对sql真的是个新手,从一周前开始,我的查询只对一条记录有效
Select m.meal_id, m.name, m.usp, m.description, m.worktime, m.proprietor, m.img, m.url, m.servings, d.name, c.name, s.name, sum(i.price / i.minamount * r.quantity) as mealPrice
from meals m
join recipe r on m.meal_id = r.meal_id
join ingredients i on i.ingredient_id = r.ingredient_id
join difficulty d on d.difficulty_id = m.difficulty_id
join cat c on c.cat_id = m.cat_id
join social s on s.social_id = m.social_id
and m.meal_id = 1
这个查询适用于一个记录,但是如果我想拥有所有的餐食(没有“and”函数),我仍然只得到一个记录,但是总和mealprice是为所有记录添加的,我如何获得所有餐食的这个查询?
我喜欢每顿饭都有一张记录和总米价
我的table:
create table meals
(
meal_id int unsigned not null auto_increment primary key,
name varchar(100) not null,
usp varchar(100) not null,
description varchar(500) not null,
worktime varchar(100) not null,
proprietor varchar(100) not null,
img varchar(100) not null,
url text not null,
servings int not null,
difficulty_id int unsigned not null,
cat_id int unsigned not null,
social_id int unsigned not null,
foreign key (difficulty_id) references difficulty (difficulty_id),
foreign key (cat_id) references cat (cat_id),
foreign key (social_id) references social (social_id)
);
create table ingredients
(
ingredient_id int unsigned not null auto_increment primary key,
name varchar(45) not null,
minamount float not null,
price float not null
);
create table recipe
(
meal_id int unsigned not null,
ingredient_id int unsigned not null,
quantity float,
primary key (meal_id, ingredient_id),
foreign key (meal_id) references meals (meal_id),
foreign key (ingredient_id) references ingredients (ingredient_id)
);
2条答案
按热度按时间6psbrbz91#
你需要下面的查询,交叉连接有助于你得到想要的结果
juud5qan2#
编辑:基于op最近的编辑;你只需要做一个
GROUP BY
.尝试:
基于op问题的前一版本:
这是一个窗口函数问题。在较新版本的mysql(>=8.0)中,您可以很容易地做到这一点。在旧版本(您的版本是5.5)中,我们可以使用会话变量来解决它。
尝试:
在mysql版本>=8.0中,我们可以使用
SUM()
作为窗口函数,在完整结果集的分区上。在这种情况下,查询将是: