从第二张表中获取计数(生成的发票数),从第三张表中获取计数(订单总数)-MySQL

时间:2019-02-26 09:50:20

标签: java mysql sql

CREATE TABLE IF NOT EXISTS `cust` (
  `cId` int(11) NOT NULL,
  `name` char(25) DEFAULT NULL,
  PRIMARY KEY (`cId`)
);

INSERT INTO `cust` (`cId`, `name`) VALUES
(1, 'Danish'),
(2, 'Dilkash'),
(3, 'Dilshad');

CREATE TABLE IF NOT EXISTS `inv` (
  `iId` int(11) NOT NULL,
  `cId` int(11) DEFAULT NULL,
  PRIMARY KEY (`iId`)
);

INSERT INTO `inv` (`iId`, `cId`) VALUES
(1, 1),
(2, 1),
(3, 1),
(4, 2),
(5, 2);

CREATE TABLE IF NOT EXISTS `ord` (
  `iId` int(11) DEFAULT NULL,
  `cId` decimal(10,0) DEFAULT NULL
);

INSERT INTO `ord` (`iId`, `cId`) VALUES
(1, '50'),
(1, '80'),
(2, '40'),
(3, '20'),
(3, '30'),
(4, '90'),
(5, '60'),
(5, '40');

我想获取客户产生的发票数量和所有订单的总和。有3个表cust,inv,ord分别代表客户,发票,订单

:::::::::::::::: WORKING FINE ::::::::::::::: 我试图使用此查询获取使用客户名称生成的发票总数...工作正常...

mysql> select cust.cId,cust.name,count(inv.iId)
from cust left join inv on cust.cId=inv.cId group by cust.cId;
+-----+---------+----------------+
| cId | name    | count(inv.iId) |
+-----+---------+----------------+
|   1 | Danish  |              3 |
|   2 | Dilkash |              2 |
|   3 | Dilshad |              0 |
+-----+---------+----------------+

:::::::::::::::: WORKING FINE ::::::::::::::: 然后我尝试获取按客户分组生成的所有发票的总和...它也可以正常工作

mysql> select cust.cId,cust.name,count(inv.iId)
from cust left join inv on cust.cId=inv.cId group by cust.cId;
+-----+---------+----------------+
| cId | name    | count(inv.iId) |
+-----+---------+----------------+
|   1 | Danish  |              3 |
|   2 | Dilkash |              2 |
|   3 | Dilshad |              0 |
+-----+---------+----------------+
3 rows in set (0.00 sec)

:::::::::::::::问题在这里::::::::::::::::::

但是当我尝试以相同的结果获得COUNT和SUM时,它无法正常工作...它是在计算订单而不是发票。

mysql> select cust.cId,cust.name,count(inv.iId),sum(ord.cId)
from cust left join inv on cust.cId=inv.cId left join ord on inv.iId=ord.iId group by cust.cId;
+-----+---------+----------------+--------------+
| cId | name    | count(inv.iId) | sum(ord.cId) |
+-----+---------+----------------+--------------+
|   1 | Danish  |              5 |          220 |
|   2 | Dilkash |              3 |          190 |
|   3 | Dilshad |              0 |         NULL |
+-----+---------+----------------+--------------+
3 rows in set (0.00 sec)

请更正我的上一个查询...它显示的是5,3,0,这是订单数量而不是发票的数量..它应该显示为3,2,0 ....

2 个答案:

答案 0 :(得分:0)

您可以使用标量子查询

DEMO

 select cust.cId,cust.name,(select count(iId) from inv b where cust.cId=b.cId ),
sum(ord.cId)
from cust left join inv on cust.cId=inv.cId left join ord on inv.iId=ord.iId 
group by cust.cId

输出:

cId name      invcnt    sum(ord.cId)
1   Danish     3         220
2   Dilkash    2         190
3   Dilshad    0    

答案 1 :(得分:0)

由于LEFT JOIN,您会变得愚蠢,对DISTINCT的相同查询应该有效,例如:

SELECT cust.cId, cust.name, COUNT(DISTINCT inv.iId), SUM(ord.cId)
FROM cust LEFT JOIN inv ON cust.cId=inv.cId 
LEFT JOIN ord ON inv.iId=ord.iId 
GROUP BY cust.cId, cust.name;

这是 SQL Fiddle