我有以下 3 个表:
crm_customers:
crm_progress:
crm_notifications:
我想要以下结果:
为了实现上述要求的输出,我使用了以下查询:
SELECT `cc`.`customer_id`, `cc`.`customer_name`, COUNT(`cp`.`progress_customer`) AS Progress, COUNT(`cn`.`notification_customer`) AS Notifications
FROM `crm_customers` AS `cc` INNER JOIN `crm_progress` AS `cp`
ON `cc`.`customer_id` = `cp`.`progress_customer`
INNER JOIN `crm_notifications` AS `cn`
ON `cn`.`notification_customer` = `cp`.`progress_customer`
WHERE `cc`.`customer_id` = 1 AND `cc`.`customer_status` = 1
但结果完全错了。但是,当我只加入 2 个表时,结果是准确的。
以下查询带来正确的输出:
SELECT `cc`.`customer_id`, `cc`.`customer_name`, COUNT(`cp`.`progress_customer`) AS Progress
FROM `crm_customers` AS `cc` INNER JOIN `crm_progress` AS `cp`
ON `cc`.`customer_id` = `cp`.`progress_customer`
WHERE `cc`.`customer_id` = 1 AND `cc`.`customer_status` = 1
我哪里做错了?如何正确使用join获取需要的结果?
最佳答案
尝试下面的查询:你需要计算与特定客户相关联的 progress_id 和 notification_id
SELECT `cc`.`customer_id`, `cc`.`customer_name`, COUNT(distinct `cp`.`progress_id`) AS Progress, COUNT(distinct `cn`.`notification_id`) AS Notifications
FROM `crm_customers` AS `cc` INNER JOIN `crm_progress` AS `cp`
ON `cc`.`customer_id` = `cp`.`progress_customer`
INNER JOIN `crm_notifications` AS `cn`
ON `cn`.`notification_customer` = `cp`.`progress_customer`
WHERE `cc`.`customer_id` = 1 AND `cc`.`customer_status` = 1
group by `cc`.`customer_id`, `cc`.`customer_name`
关于mysql - 如何使用 mysql inner join 计算其他表中的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52419828/