gpt4 book ai didi

mysql - 帮助 mysql 连接/分组

转载 作者:行者123 更新时间:2023-11-29 14:45:08 26 4
gpt4 key购买 nike

我会尝试让这变得简单。

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

由于某种原因,如果用户有 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

最佳答案

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

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

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

关于mysql - 帮助 mysql 连接/分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7113705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com