如何使用mysql内部联接计数其他表中的行数?

时间:2018-09-20 07:29:44

标签: mysql

我有以下3张桌子:

crm_customers:

enter image description here

crm_progress:

enter image description here

crm_notifications:

enter image description here

我想要以下结果:

enter image description here

要实现上述要求的输出,我正在使用以下查询:

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

我在哪里做错了?如何正确使用联接来获取所需的结果?

2 个答案:

答案 0 :(得分:1)

请尝试以下查询:您需要计算与某些客户相关联的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`

答案 1 :(得分:0)

可以使用以下查询来实现:

var complaintsData