如何解决有没有更好的方法来执行这个 SQL 查询?
我编写了这个 SQL 查询来获取我数据库中每个客户的数据。
如您所见,我正在尝试获取未付款订单总数和我查询的订单总数。
我最后的目标是只获得未付款订单的用户(我想我必须在查询结束时使用 HAVING
)。
这是我的查询
SELECT
u.id,u.first_name,u.last_name,u.email,u.phone,(SELECT COUNT(*) FROM account_order WHERE account_order.user_id = u.id AND account_order.is_paid = False AND account_order.max_meals > 0) as total_not_paid,(SELECT COUNT(*) FROM account_order WHERE account_order.user_id = u.id) AS total_orders
FROM account_user u
您认为有更好的方法来获取记录吗?
如何才能获得只有一个 total_not_paid
和只有一个 total_order
的用户?
解决方法
如果您想要未付款的订单,您可以使用显式聚合和 having
子句:
SELECT u.*,COUNT(*) FILTER (WHERE NOT is_paid AND ao.max_meals > 0) as total_not_paid,COUNT(*) AS total_orders
FROM account_user u JOIN
account_order ao
ON ao.user_id = u.id
GROUP BY u.id
HAVING COUNT(*) FILTER (WHERE NOT is_paid AND ao.max_meals > 0) > 0;
,
您可以按如下方式使用条件聚合:
SELECT u.id,u.first_name,u.last_name,u.email,u.phone,count(case when ao.is_paid = False AND ao.max_meals > 0 then 1 end)
as total_not_paid,count(ao.*) AS total_orders
FROM account_user u
left join account_order ao on account_order.user_id = u.id
group by u.id;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。