Monday, March 13, 2017

SELECT count(*) with where produces weird values

It seems when I am trying to make a query to get the users transaction sum, it does not return the proper value until I remove the filter on code, what is even more interesting is the filter on the bar code following works perfectly fine, it seems maybe there is an inconsistency between both the subqueries in the WHERE clause?

Explanation:

With the below query, when I remove the and code != "foo" AND code !="foobar" from the query, it returns the correct value, but I also tried changing it to code = "foo" or code = "foobar" to check if any of the results had these codes, and it returns null when I do this.

SELECT SUM(transactions.amount)
FROM `transactions`
WHERE `transactions`.`deleted_at` IS NULL
    AND `transactions`.`user_id` = 80
    AND `transactions`.`user_id` IS NOT NULL
    AND `manually_deleted_at` IS NULL
    AND
            (SELECT count(*)
             FROM `transaction_subcategories`
             WHERE `transactions`.`transaction_subcategory_id` = `transaction_subcategories`.`id`
                     AND `code` != "foo"
                     AND `code` != "foobar"
                     AND
                             (SELECT count(*)
                              FROM `transaction_categories`
                              INNER JOIN `transaction_categories_transaction_subcategories` ON `transaction_categories`.`id` = `transaction_categories_transaction_subcategories`.`transaction_category_id`
                              WHERE `transaction_categories_transaction_subcategories`.`transaction_subcategory_id` = `transaction_subcategories`.`id`
                                      AND `code` = "bar") >= 1) >= 1
    AND `posted_date` BETWEEN "2016-04-01 00:00:00.000000" AND "2017-03-31 23:59:59.000000"
    AND `parent_id` = 0;

While I do realize this is a mysql query issue, the laravel ORM code is a bit cleaner:

    $income_transactions = \Auth::user ()->transactions ()
    ->notManuallyDeleted()
    ->whereHas('transactionSubcategory', function ($query) {
        $query
        ->where('code', '!=', 'foo')
        ->where('code', '!=', 'foobar')
        ->whereHas('transactionCategories', function ($query2){
            $query2->where('code', '=', 'bar');
        });
    })
    ->whereBetween ( 'posted_date', [$from,$to])
    ->where('parent_id', '=', 0)
    ->get ();



via nerdsville

Advertisement