laravel如何写这种的sql语句?

情况是这样,我建立一张水果每日销量表

CREATE TABLE `shuiguo` (
  `id` int(11) NOT NULL,
  `type` varchar(255) DEFAULT NULL COMMENT '类型,包括苹果,香蕉,梨,葡萄,西瓜',
  `value` varchar(10) DEFAULT NULL COMMENT '销量',
  `day` varchar(10) DEFAULT NULL COMMENT '日期'
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4

我想着想知道某个日期的苹果,梨,葡萄 销量
最简单sql语句有

select `value` from shuiguo where `type`='苹果' and day='日期';
select `value` from shuiguo where `type`='梨'  and day='日期';
select `value` from shuiguo where `type`='葡萄'  and day='日期';

我就需要执行三次sql语句,有没有一条语句就能搞定的?
然后如何我想要一段日期内的那三种水果的销量,sql语句要怎么写的?

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
讨论数量: 8
ShuiguoModel::selectRaw('sum(value) as value')->groupBy('type','day')->get();
4个月前 评论
// 指定日期 $date = ' 日期 ';

// 查询苹果、梨和葡萄的值
 $appleQuery = DB::table ('shuiguo') ->select ('value', DB::raw ("' 苹果 ' as type")) ->where ('type', ' 苹果 ') ->where ('day', $date);

$pearQuery = DB::table ('shuiguo') ->select ('value', DB::raw ("' 梨 ' as type")) ->where ('type', ' 梨 ') ->where ('day', $date);

$grapeQuery = DB::table ('shuiguo') ->select ('value', DB::raw ("' 葡萄 ' as type")) ->where ('type', ' 葡萄 ') ->where ('day', $date);

// 合并查询
 $results = $appleQuery ->unionAll ($pearQuery) ->unionAll ($grapeQuery) ->get (); 
4个月前 评论
keyboby 4个月前
//某个日期
ShuiGuo::query()
    ->whereIn('type', ['苹果','梨','葡萄'])
    ->where('day','=', '日期')
    ->groupBy('type','value')
    ->get(['type','value']);
//select `type`, `value` from `shui_guo` where `type` in ('苹果', '梨', '葡萄') and `day` = '日期' group by `type`, `value` 

//某个时间段
ShuiGuo::query()
    ->whereIn('type', ['苹果','梨','葡萄'])
    ->whereBetween('day',['日期开始','日期结束'])
    ->groupBy('type')
    ->selectRaw("type,sum(value) as sum_value")
    ->get();
//select type,sum(value) as sum_value from `shui_guo` where `type` in ('苹果', '梨', '葡萄') and `day` between '日期开始' and '日期结束' group by `type` 
4个月前 评论
donggan (楼主) 4个月前
ShuiguoModel::selectRaw('type,day,sum(value) as value')
->whereBetween('day', [start_day,end_day])
->whereIn('type', ["苹果","葡萄","梨"])
->groupBy('type','day')->get();
4个月前 评论
Mutoulee

想知道某个日期的苹果,梨,葡萄 销量 :

$data = DB::table ('shuiguo')
    ->whereIn('type', ['苹果', '梨', '葡萄'])
    ->where('day', $day)
    ->get();

想要一段日期内的那三种水果的销量:

$data = DB::table ('shuiguo')
    ->whereIn('type', ['苹果', '梨', '葡萄'])
    ->whereBetween('day', [$day1, $day2])
    ->get()
    ->groupBy('type')
foreach($data as $group){
    // 该时间段内每一种水果的销量
    echo $group->pluck('value')->sum();
}

没测试过,仅供参考。

4个月前 评论

select * from t where (name,type) in (('张三','A'),('李四','B'),('王五','C'))

4个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!