我需要从一个表(tbl_b)获取用户结果,并获取另一个表(tbl_a)的ID计数。
tbl_b:
ID NAME LAST_NAME UNTIL_DATE
================================================
1 Sharon Alexander 2016-04-01
2 David Lynn 2014-04-01
3 Jason Rominsky 2015-04-01
tbl_a:
ID
==
1
2
3
4
5
6
(显然是错误的)查询:
SELECT tbl_b.ID, tbl_b.NAME, tbl_b.LAST_NAME, COUNT(tbl_a.ID) as TOTAL
FROM tbl_a, tbl_b
WHERE tbl_b.UNTIL_DATE>=NOW()
我需要从tbl_b中选择一个人员列表以及来自tbl_a的总登录数(每个登录名都有一个ID)。
如果tbl_b为空或UNTIL_DATE小于NOW()
,则TOTAL的结果将等于0,这是错误的。 (结果必须是正数)
答案 0 :(得分:2)
使用相关的子查询来计算:
GROUP BY
或者使用SELECT tbl_b.ID, tbl_b.NAME, tbl_b.LAST_NAME, COUNT(tbl_a.ID) as TOTAL
FROM tbl_b LEFT JOIN tbl_a ON tbl_a.id = tbl_b.id
WHERE tbl_b.UNTIL_DATE >= NOW()
GROUP BY tbl_b.ID, tbl_b.NAME, tbl_b.LAST_NAME
执行左外连接:
dictionary1 = {1: '5', 2: '8', 3: '4'}
dictionary2 = {1: '3', 2: '5', 3: '7'}
dictionary3 = {1: '1', 2: '2', 3: '3'}
答案 1 :(得分:1)
试试这个,我使用MSSQL
SELECT tbl_b.ID, tbl_b.NAME, tbl_b.LAST_NAME, ISNULL(Logins.TOTAL_LOGINS, 0) as TOTAL
FROM tbl_b
LEFT JOIN
(SELECT ID, COUNT(*) as TOTAL_LOGINS FROM tbl_a GROUP BY ID) as Logins
ON tbl_b.ID = Logins.ID WHERE tbl_b.UNTIL_DATE >= NOW ()