帮助mysql连接/分组

时间:2011-08-18 20:27:23

标签: mysql

我会尽力做到这一点。

此查询列出了我的网站用户,他们的总订单,卡片和存档地址。

出于某种原因,如果用户有2个地址但只有1个订单,则会显示客户有2个订单。

例如:user4实际上只有1个订单,但是显示2 ,我假设它,因为他有2个地址,并且它与连接或分组有关。

SELECT
users.user_email,
users.user_firstname,
users.user_lastname,
users.user_joindate,
users.user_logindate,
Count(users_addresses.usera_id) AS count_addr,
Count(users_cards.userc_id) AS count_cards,
Count(orders.order_id) AS count_orders,
Sum(orders.order_total) AS sum_ordertotal
FROM
users
LEFT JOIN users_addresses ON users_addresses.usera_userid = users.user_id
LEFT JOIN users_cards ON users_cards.userc_userid = users.user_id
LEFT JOIN orders ON orders.order_userid = users.user_id
GROUP BY
users.user_id
ORDER BY user_id DESC
LIMIT 5

示例输出:

userid | orders | addresses | cards
------ ----------------------------
user4  |   2    |     2     |   0
user3  |   0    |     0     |   0
user2  |   1    |     1     |   0
user1  |   0    |     1     |   0

2 个答案:

答案 0 :(得分:1)

一种可能性是使用COUNT(DISTINCT orders.order_id)。但是,这对Sum()没有帮助。

另一种可能性(albiet效率较低)是使用子查询进行计数。

SELECT
    users.user_email,
    users.user_firstname,
    users.user_lastname,
    users.user_joindate,
    users.user_logindate,
    (SELECT count(*) FROM users_addresses WHERE users_addresses.usera_id = users.user_id) AS count_addr,
    (SELECT count(*) FROM user_cards WHERE users_cards.userc_id = users.user_id) AS count_cards,
    Count(orders.order_id) AS count_orders,
    Sum(orders.order_total) AS sum_ordertotal
FROM users
LEFT JOIN orders ON orders.order_userid = users.user_id
GROUP BY users.user_id
ORDER BY user_id DESC
LIMIT 5

答案 1 :(得分:0)

如前所述:

count(distinct(orders.order_id)) as count_orders

你可以使用:

(select sum(order_total) from orders where user_id = users.user_id) as sum_ordertotal