有没有更好的方法来执行此 SQL 查询?
Is there a better way to execute this SQL query?
我写了这个 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
的用户?
您可以按如下方式使用条件聚合:
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;
如果您想要未付款订单,您可以使用显式聚合和 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;
我写了这个 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
的用户?
您可以按如下方式使用条件聚合:
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;
如果您想要未付款订单,您可以使用显式聚合和 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;