2013-05-31 89 views
0

我有2个表,我目前正在使用。客户表和他们拥有的发薪日贷款表。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

您实际上并没有将关键字'NULL'作为字符串存储在'outstandingcurrentamount'(否则将是数字?)列中,是吗? –

+0

请为这两个表中的每一个发布“CREATE TABLE”语句。 –

+0

没有它的数据库分配的默认NULL。但出于某种原因,执行outstandingcurrentamount> = 0将返回所有记录 – user1992522

回答

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 
+0

之前子查询的目的是什么?为什么不直接运行子查询并从中选择想要的列? –

+1

@PugganSe目的是让'tblcustomer'中的所有列不属于“GROUP BY”的一部分,这是“普通”RDBMSes(Oracle,SQL Server)所不允许的。虽然它在MySql中是允许的,但它不是一个好主意,因为从理论上讲,无法分辨组中哪个值为每个这样的列获取。另一种方法是在这样的列上使用集合函数'MIN(),MAX()...'。 – peterm

+0

感谢您的信息,我自己只使用mysql,因此只知道mysql可以做什么,但总是很高兴能够更好地了解其他人 –

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; 
+0

语法错误(对不起,我不知道MySQL的最好的sytax)。左加入(tblloan.fkcustomerid = tblcustomer.pkcustomerid) – user1992522

+0

和+1不是NULL' – rinchik

+0

对不起,表名应该在 –