Php 如何使用join计算mysql?
一、 我使用laravel开发销售仪表板,需要计算每天的销售数量。我有两个表,产品和交易。在产品中,我拥有所有产品,在交易中,我拥有所有销售交易 通过此查询,我可以按产品名称获得销售组的编号Php 如何使用join计算mysql?,php,mysql,laravel,eloquent,Php,Mysql,Laravel,Eloquent,一、 我使用laravel开发销售仪表板,需要计算每天的销售数量。我有两个表,产品和交易。在产品中,我拥有所有产品,在交易中,我拥有所有销售交易 通过此查询,我可以按产品名称获得销售组的编号 $dash = Transactions::select(DB::raw('`product_name` AS ProductName, COUNT(`cod_sale`) as `TotalSale`')) ->where('status_sale', '=', 'Finished'
$dash = Transactions::select(DB::raw('`product_name` AS ProductName, COUNT(`cod_sale`) as `TotalSale`'))
->where('status_sale', '=', 'Finished')
->where('date_finished', '>=', $data)
->groupBy('product_name')
->get();
这是一个问号
[
{
"ProductName": "Product A",
"TotalSale": 15
},
{
"ProductName": "Product B",
"TotalSale": 2
},
{
"ProductName": "Product C",
"TotalSale": 1
},
{
"ProductName": "Product D",
"TotalSale": 9
}
]
如何退回未销售到零的产品?请记住,表中的交易只是销售的产品,表中的产品是所有产品
我想以这种方式返回:
[
{
"ProductName": "Product A",
"TotalSale": 15
},
{
"ProductName": "Product B",
"TotalSale": 2
},
{
"ProductName": "Product C",
"TotalSale": 1
},
{
"ProductName": "Product D",
"TotalSale": 9
},
{
"ProductName": "Product E",
"TotalSale": 0
},
{
"ProductName": "Product F",
"TotalSale": 0
}
使用此代码可能会对您有所帮助
$dash = Transactions::select(DB::raw('`product_name` AS ProductName, COUNT(`cod_sale`) as `TotalSale`'))
->where('status_sale', '=', 'Finished')
->where('date_finished', '>=', $data)
->where(DB::raw('COUNT(`cod_sale`)' '>', 0)
->groupBy('product_name')
->get();
使用
左连接
:
Product::leftJoin('transactions', function($join) use($date) {
$join->on('products.id', '=', 'transactions.product_id')
->where('status_sale', 'Finished')
->where('date_finished', '>=', $date);
})
->groupBy('products.id')
->get([
'products.name as ProductName',
DB::raw('count(transactions.id) TotalSale')
]);
不幸的是,我不能做任何提示,我最终学会了其他东西,这是有用的!但我决定让系统每天在表中插入所有产品的交易,销售数量=0,我将计数函数改为总和,因此,它添加了某个产品的销售额,而不是表中的行数。您基本上需要产品表与交易表的左连接。您需要
产品E
和产品F
的记录来exist@MadhurBhaiya,你能给我举个例子吗?没有退货的产品没有销路你想要什么不能理解