table account:
acID (pri, uni, a-i)
...
table patient:
paID (pri, uni, a-i)
paAccountID (int, foreign key)
...
table test:
tsID (pri, uni, a-i)
tsAccountID (int, foreign key)
tsPatientID (int, foreign key)
tsStatus (int, ranges 0 to 3)
tsFlag (int, ranges 0 to 1)
为每位患者检索patient
的数据和tsID
的数量:
SELECT patient.*, Count(tsID) as tsCount
FROM account
LEFT JOIN patient ON acID = paAccountID
LEFT JOIN test ON paID = tsPatientID
WHERE paAccountID=1
GROUP BY paID
现在,我想检索tsFlag=1
的数量,tsStatus=0
的数量,'tsStatus = 1'的数量...... tsStatus=3
的数量。
感谢Explosion Pill的回答:
SELECT patient.*, Count(tsID), SUM(tsStatus=0),
SUM(tsStatus=1), SUM(tsStatus=2), SUM(tsStatus=3), SUM(tsFlag=1)
FROM account
LEFT JOIN patient ON acID = paAccountID
LEFT JOIN test ON paID = tsPatientID
WHERE paAccountID=1
GROUP BY paID
像魅力一样工作,但如果NULL
为SUM
提供Count=0
- 我怎样才能获得0
?
答案 0 :(得分:3)
您可以使用SUM
:
SELECT patient.*, SUM(tsStatus = 1) AS tsStatus1
FROM ...
您也可以为其他列执行此操作。
您可以使用IFNULL
或COALESCE
指定默认的非空值:
IFNULL(SUM(tsStatus = 3), 0);