SQL查询给出了奇怪的结果 - 计算

时间:2016-01-30 19:48:15

标签: mysql left-join inner-join

这是我的SQL查询:

select 
client_details.client_id, 
count( PC.cheque_status ) as count_stat, 
client_details.client_city, 
client_details.account_created_on, 
client_details.client_name, 
SUM(PC.amount), 
SUM(PNB.amount), 
SUM(PCA.amount), 
PC.cheque_status, 
count(PNB.status), 
count(PCA.status), 
PSD.version 
                      from `client_details` as `client_details` 
                      inner join `products_sold_details` as `PSD` on `PSD`.`client_id` = `client_details`.`client_id` and PSD.version = 1
                      left join product_cheque_mapped PCM on PCM.product_sold_id = PSD.id
                      left join product_cash_mapped PCAM on PCAM.product_sold_id = PSD.id
                      left join product_neft_mapped PNM on PNM.product_sold_id = PSD.id
                      left join `product_cheques` as `PC` on (`PC`.`cheque_status` = 0 and PCM.product_cheques_id = PC.id)                          
                      left join `product_net_banking` as `PNB` on ( `PNB`.`status` = 0 and PNM.product_neft_id = PNB.id)
                      left join `product_cash` as `PCA` on ( `PCA`.`status` = 0 and PCAM.product_cash_id = PCA.id )
                      group by `client_details`.`client_id`, PCM.product_cheques_id having count( PC.cheque_status ) > 0

这些是表结构:

client_details:
client_id (PK);
client_name;

products_sold_details:
id (PK);
client_id (FK);
version;

product_cheques:
id (PK);
client_id (FK);
amount;
cheque_status;

product_net_banking:
id (PK);
client_id (FK);
amount;
status;

product_cash:
id (PK);
client_id (FK);
amount;
status;

products_sold_details与product_cheques,product_net_banking,product_cash

有多对多的关系

client_details有很多products_sold_details client_details有许多product_cheques,product_cash,product_net_banking

如果客户端有两个产品,并且只有一个检查合并产品的状态为0,那么我应该将计数(PC.cheque_status)设为1

如果客户端有3个产品,并且该客户端有3个检查状态为0,那么我应该将计数(PC.cheque_status)作为3进行3次检查。 但是,在这种情况下,我得到的是9作为计数(PC.cheque_status)。

此外,SUM(金额)乘以产品数量。

我在哪里错了?

0 个答案:

没有答案