score score - 5 months ago 33
MySQL Question

Laravel SUM of multiple fields return null with raw query

The following is my query :

$sales = DB::table('sales')
->leftJoin('category_sales', 'category_sales.sale_id', '=', 'sales.id')
->leftJoin('department_sales', 'department_sales.sale_id', '=', 'sales.id')
->leftJoin('store_configs', 'store_configs.id', '=', 'sales.store_config_id')
->select('sales.date',
DB::raw('store_configs.store_dba'),
DB::raw('sales.id'),
DB::raw('(sales.taxable + sales.non_taxable + category_sales.amount + department_sales.amount) as total_sales'),
DB::raw('0.0825*(sales.taxable + category_sales.amount + department_sales.amount) as total_tax'))
->groupBy('date')->orderBy('date', 'desc')
->get();


I get the right value when I have values on
category_sales and department_sales
table. Lets say, I do not have any
amount value for the sales_id in category_sales
table, the final result for
total_sales
and
total_tax
is null.

My question is : how would I still sum the values of fields if the data is present ?

taxable, non_taxable, and amount'


in
category_sales and department_sales

are integer with
defaults
to
0


My table structure just for an idea and is similar with department_sales:

CREATE TABLE `category_sales` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`amount` int(11) NOT NULL DEFAULT '0',
`category_id` int(10) unsigned DEFAULT NULL,
`sale_id` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `category_sales_category_id_index` (`category_id`),
KEY `category_sales_sale_id_index` (`sale_id`),
CONSTRAINT `category_sales_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE,
CONSTRAINT `category_sales_sale_id_foreign` FOREIGN KEY (`sale_id`) REFERENCES `sales` (`id`) ON DELETE CASCADE) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Answer

You can wrap nullable fields into IFNULL() function, something like this:

DB::raw('(IFNULL(sales.taxable,0)
 + IFNULL(sales.non_taxable,0)
 + IFNULL(category_sales.amount,0)
 + IFNULL(department_sales.amount,0)
) as total_sales'),
DB::raw('0.0825*(IFNULL(sales.taxable,0) 
 + IFNULL(category_sales.amount,0)
 + IFNULL(department_sales.amount,0)) as total_tax'))