2015-05-13 87 views
-1

我需要從一個表(tbl_b)獲取用戶結果並獲得另一個表(tbl_a)的ID的計數。需要從另一個表中添加COUNT COUNT到另一個表中

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,這是錯誤的。 (結果必須是正號)

回答

2

使用相關子查詢數:

SELECT tbl_b.ID, tbl_b.NAME, tbl_b.LAST_NAME, 
     (select COUNT(*) from tbl_a where tbl_a.id = tbl_b.id) as TOTAL 
FROM tbl_b 
WHERE tbl_b.UNTIL_DATE >= NOW() 

或者做一個左外連接與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 
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() 
相關問題