MySQL Query在Query中计算2层深度的记录数

时间:2013-05-31 20:03:44

标签: mysql

我目前正在使用2张桌子。客户表和他们的发薪日贷款表。

我写的查询需要获得未偿还贷款的客户数量如下:

 SELECT * FROM tblcustomer
 WHERE pkcustomerid IN
     (SELECT fkcustomerid
     FROM
        (SELECT * FROM tblloan
        WHERE outstandingcurrentamount!="NULL") AS T)

如果客户数据的未结金额不是NULL或0,则返回客户数据列表。现在我需要循环此结果并对每个客户执行单独查询以获得所有贷款。但我只需要点数。

有没有办法以某种方式为查询返回的数据添加一个额外的列,该列是该客户的贷款计数?

表格结构的相关部分:

CREATE TABLE IF NOT EXISTS `tblcustomer` (
  `pkcustomerid` bigint(20) NOT NULL AUTO_INCREMENT,
  `fkuserid` int(11) NOT NULL,
  `fkstoreid` int(11) NOT NULL,
  `fkcompanyid` int(11) NOT NULL,
  `fkstaticid` varchar(255) NOT NULL,
   ...snip...
  PRIMARY KEY (`pkcustomerid`,`fkcountryid`,`fkcityid`,`fkstateid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=821 ;


CREATE TABLE IF NOT EXISTS `tblloan` (
  `pkloanid` int(11) NOT NULL AUTO_INCREMENT,
  `fkuserid` int(11) NOT NULL,
  `fkcustomerid` int(11) NOT NULL,
  `fkstoreid` int(11) NOT NULL,
  `outstandingcurrentamount` double NOT NULL
  ...snip...
  PRIMARY KEY (`pkloanid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1567 ;

2 个答案:

答案 0 :(得分:2)

尝试

SELECT t.*, q.loan_count 
  FROM tblcustomer t JOIN 
(
 SELECT c.pkcustomerid, COUNT(*) loan_count 
   FROM tblcustomer c LEFT JOIN  tblloan l 
     ON c.pkcustomerid = l. fkcustomerid
  WHERE l.outstandingcurrentamount IS NOT NULL 
    AND l.outstandingcurrentamount > 0
  GROUP BY c.pkcustomerid
) q ON t.pkcustomerid = q.pkcustomerid

答案 1 :(得分:1)

通过使用JOIN而不是子查询,您可以从所有表中选择内容, 然后使用GROUP BY为每个客户获取一行,并使用COUNT(*)计算该行的组合总数=贷款数量

SELECT COUNT(*), tblcustomer.*
FROM tblloan 
LEFT JOIN tblcustomer ON (tblloan.fkcustomerid = tblcustomer.pkcustomerid) 
WHERE tblloan.outstandingcurrentamount IS NOT NULL
GROUP BY tblcustomer.pkcustomerid;