SELECT count(*),其中where产生奇怪的值

时间:2017-03-13 18:36:00

标签: mysql laravel

当我尝试进行查询以获取用户事务总和时,它似乎没有返回正确的值,直到我删除代码上的过滤器,更有趣的是条形码后面的过滤器工作完美好吧,似乎WHERE子句中的两个子查询之间可能存在不一致吗?

说明:

使用下面的查询,当我从查询中删除和代码!=“foo”AND code!=“foobar”时,它返回正确的值,但我也尝试将其更改为code =“foo”或代码=“foobar”来检查是否有任何结果有这些代码,并且当我这样做时它返回null。

SELECT SUM(t.amount)
FROM transactions t
WHERE `t`.`deleted_at` IS NULL
    AND `t`.`user_id` = 80
    AND `t`.`user_id` IS NOT NULL
    AND `manually_deleted_at` IS NULL
    AND
            (SELECT count(*)
             FROM `transaction_subcategories` s
             WHERE `t`.`transaction_subcategory_id` = `s`.`id`
                     AND `code` != "foo"
                     AND `code` != "foobar"
                     AND
                             (SELECT count(*)
                              FROM `transaction_categories` c
                              INNER JOIN `transaction_categories_transaction_subcategories` sc ON `c`.`id` = `sc`.`transaction_category_id`
                              WHERE `sc`.`transaction_subcategory_id` = `s`.`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;

虽然我确实知道这是一个mysql查询问题,但laravel ORM代码更清晰一点:

    $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 ();

更新 不确定这是否有帮助,但我做了一个查询,看看它返回哪个子类别与WHERE子句,它只返回代码为NULL的子类别 MySQL的> SELECT * FROM transaction_subcategories WHERE id in('1125','630','1395')AND code is null;

+------+-----------------------------------+------+---------+
| id   | name                              | code | user_id |
+------+-----------------------------------+------+---------+
|  630 | foo                               | NULL |      80 |
| 1125 | foo                               | NULL |      80 |
| 1395 | foo                               | NULL |      80 |
+------+-----------------------------------+------+---------+

更新2 原来是WHERE这样做,似乎不会将NULL值与字符串进行比较,换句话说,如果我对具有空值的列执行WHERE,空值行将消失

回答结果在WHERE子句中添加OR code is null组是我所需要的。关闭:))

0 个答案:

没有答案