我需要在MySql DB中查询客户数据。
我有客户表,订单和连接表。
我需要找到最后一次访问 - MAX(connection.date_add)
以及订单的总和。
我厌倦了在一个查询中执行此操作 -
select MAX( connection.date_add), SUM(order.total_paid)
from customer
join order on customer.id = order.c_id
join connection on customer.id = connection.c_id
问题是结果每个连接有1行,订单数乘以连接数
我通过执行3次查询解决了这个问题,而不是合并结果"手动"
我的问题:是否可以在一个查询中完成?
我知道在其他SQL dbs中你可以使用WITH语句,但在一个查询中是否有一种简单的方法在MySql中执行它?
无法添加答案 - 所以这是解决方案 -
SELECT c.id_customer,
COUNT(DISTINCT o.id_order ) AS '# VALID ORDERS',
MAX( co.`date_add` ) AS last_visit,
SUM( o.total_paid )*COUNT(DISTINCT o.id_order )/COUNT(co.`date_add` ) AS '$ (TOTAL AMOUNT)'
FROM ps_customer AS c
JOIN ps_orders o ON ( c.id_customer = o.id_customer )
JOIN ps_connections co ON co.id_customer = g.id_customer
group by c.id_customer
内部子查询的解决方案也有效,但速度太慢。
Stackoverflow - 这不重复,请仔细阅读。
答案 0 :(得分:1)
您需要在 join
之前使用子查询:
select MAX(co.date_add), o.total_paid
from customer cu join
(select c_id, sum(o.total_paid) as total_paid
from order o
group by c_id
) o
on cu.id = o.c_id join
connection co
on cu.id = co.c_id
我猜你也想要一个group by cu.id
,所以每个客户都会得到一行。
select co.maxda, o.total_paid
from customer cu join
(select c_id, sum(o.total_paid) as total_paid
from order o
group by c_id
) o
on cu.id = o.c_id join
(select co.c_id, max(co.date_add) as maxda
from connection co
group by co.c_id
) co
on cu.id = co.c_id
group by cu.id;