注:优化group by语句:对某一个字段进行分组时的时候,Mysql默认会进行排序,而业务不需要分组,需补充order by null 提高查询效率。
1.查询价格低于10元的菜品的名称,价格及其菜品的分类名称
select a1.name,a1.price,a2.name from dish a1 join category a2 on a1.category_id=a2.id where a1.price <10;
2.查询所有价格在 10元(含)到50元(含)之间 且 状态为"起售"的菜品名称、价格及其分类名称 (即使菜品没有分类 , 也要将菜品查询出来)
select a1.name,a2.name,a1.price from dish a1 left join category a2 on a1.category_id=a2.id where a1.price between 10 and 50 and a1.status=1;
3.查询每个分类下最贵的菜品, 展示出分类的名称、最贵的菜品的价格
select a2.name,max(a1.price) from dish a1 , category a2 where a1.category_id = a2.id group by a2.name;
4.查询各个分类下 菜品状态为 "起售" , 并且 该分类下菜品总数量大于等于3 的 分类名称
select a2.name ,count(*) from dish a1 , category a2 where a1.category_id = a2.id and a1.status=1 group by a2.name having count(*)>=3;
5.查询出 "商务套餐A" 中包含了哪些菜品 (展示出套餐名称、价格, 包含的菜品名称、价格、份数)
SELECT a2.name, a2.price, a1.name, a2.price, c.copies FROM dish a1 JOIN setmeal_dish c ON a1.id = c.dish_id JOIN setmeal a2 ON a2.id = c.setmeal_id WHERE a2.name = '商务套餐A';
6.查询出低于菜品平均价格的菜品信息 (展示出菜品名称、菜品价格)
select * from dish a where price < (select avg(price) from dish);