所以我一直在处理查询几年, 有时我会问自己是否有更简单的方法, 或者更复杂的方式使其发挥作用。所以今天我遇到了一个情况,我有一张桌子,让我们说用户,我想对那张桌子进行几次比较。
在这种情况下,从我拥有的每个用户那里获取统计数据:了解他所做的订单数量,或者他在指定时间段内在愿望清单中有多少产品;例如上周和本周。
所以我想知道的是,最好的方法是使用left joins
和ifs
这样:
SELECT
users.id,
SUM(IF(wishlist.date = LAST_WEEK, 1, 0)) LAST_WEEK_WISHLIST,
SUM(IF(wishlist.date = THIS_WEEK, 1, 0)) THIS_WEEK_WISHLIST,
SUM(IF(orders.date = LAST_WEEK, 1, 0)) LAST_WEEK_ORDERS,
SUM(IF(orders.date = THIS_WEEK, 1, 0)) THIS_WEEK_ORDERS
FROM
users
LEFT JOIN wishlist ON users.id = wishlist.user_id
LEFT JOIN orders ON users.id = orders.user_id
...
GROUP BY users.id
ORDER BY users.id ASC
......或者是否有更好或更优化的方法来实现这一目标。
提前致谢
答案 0 :(得分:-2)
我建议尝试使用子查询而不是加入这可能会产生影响
这是我如何解决这个问题的一个例子
SELECT l_outer.Locations_LocationID, l_outer.Locations_LocationName,
ifnull((SELECT format(sum(replace(Payments_Amount, '$', '')), 2) as card_total
FROM Payments as p
where p.Payments_PaymentItem in ('Visa', 'MasterCard', 'Discover') AND p.Payments_LocationID = l_outer.Locations_LocationID AND STR_TO_DATE(Payments_Date, '%m/%d/%Y') >= DATE_SUB(curdate(),INTERVAL (DAY(curdate())-1) DAY)
group by p.Payments_LocationID), 0.00) Cards,
ifnull((SELECT format(sum(replace(Payments_Amount, '$', '')), 2) as AmericanExpress_total
FROM Payments as p
where p.Payments_PaymentItem = 'American Express' AND p.Payments_LocationID = l_outer.Locations_LocationID AND STR_TO_DATE(Payments_Date, '%m/%d/%Y') >= DATE_SUB(curdate(),INTERVAL (DAY(curdate())-1) DAY)
group by p.Payments_LocationID), 0.00) AmericanExpress
From Locations as l_outer