我有以下统计表:

id | date | user_id | price | additional_price


我的查询如下所示:

SELECT month, sum(price), sum(additional_price)
FROM statistics s
INNER JOIN users u on s.user_id = u.id
AND u.confirmed = 1
GROUP BY MONTH(date);


问题是此表中存在行,其中行的价格等于0,但additional_price大于0,其中用户未被确认或不再存在。我想将它们计入输出总和。就像是:

SELECT t.month, sum(t.price), sum(t.additional_price)
FROM (

(SELECT month, sum(price), sum(additional_price)
FROM statistics s
INNER JOIN users u on s.user_id = u.id
WHERE u.confirmed = 1
AND s.price > 0
GROUP BY MONTH(date))
UNION
(SELECT month, sum(price), sum(additional_price)
FROM statistics s
WHERE price = 0
GROUP BY MONTH(date))

) AS t
GROUP BY MONTH(t.date);


它将起作用,这就是我想要实现的结果。但是查询很慢,很大,而且难以维护。我遇到的主要问题是我不能在像这样的表上使用关系:

$statistics = Statistic::join('users');
$statisticsForZeroPrice = Statistic::forZeroPrice();
$result = DB::query()->fromSub($statistics->union($statisticsForZeroPrice), 't')
 ->with('user') // will not work
 ->groupBy('t.date')
 ->get();


有没有更简单的解决方案来解决这个问题?

最佳答案

我猜您想要一个left join。从您问题中的有限信息来看,类似以下内容:

SELECT month, sum(price), sum(additional_price)
FROM statistics s LEFT JOIN
     users u
     ON s.user_id = u.id AND u.confirmed = 1
GROUP BY MONTH(date);


不清楚哪个表应该在left join中最先出现。

关于php - 内连接(一种情况除外),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60019771/

10-10 02:56