0

我目前正在使用 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 ;
4

2 回答 2

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
于 2013-05-31T20:12:58.493 回答
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;
于 2013-05-31T20:10:58.507 回答