回答

收藏

MySQL COUNT,具有GROUP BY和零项

技术问答 技术问答 212 人阅读 | 0 人回复 | 2023-09-12

我有两张桌子:. l! t* _7 M- e' i7 ?8 ?4 r+ V
表1.    options_ethnicity具有以下条目:
5 x+ j  T5 d9 S+ uethnicity_id ethnicity_name  1 White  2 Hispanic  3 African/American表2.    inquiries以下条目:* f4 v! o) X+ Y: J0 R" ]
inquiry_id ethnicity_id 1 1 1 2 1 3 1 4 2 5 2 根据种族显示,我想生成一个查询数量的表。到目前为止,我的查询看起来像这样:$ N8 D; m2 Z: Q) X3 h' A2 d! ^
SELECT options_ethnicity.ethnicity_name,COUNT('inquiries.ethnicity_id') AS countFROM (inquiries     LEFT JOIN options_ethnicity ON    options_ethnicity.ethnicity_id = inquiries.ethnicity_id)  GROUP BY options_ethnicity.ethnicity_id查询给出了正确的答案,但没有针对非洲/美洲,结果为0。
; A% L& R3 F+ Q5 ?/ d( I. OWhite 3  Hispanic 2如果我用RIGHT JOIN代替LEFT JOIN,我会得到三个种族的名字,但是非洲裔/美洲裔的计数是错误的。2 @: S0 `0 K, h% e
White 3  Hispanic 2  African/American 1感谢任何帮助。' d8 {+ t. J8 `' F1 Z9 ^& k
这个帖子的更新,似乎有一个有效的查询:
2 w: {, l9 U8 U0 ]8 BSELECT     options_ethnicity.ethnicity_name,    COALESCE(COUNT(inquiries.ethnicity_id),0) AS count FROM options_ethnicity LEFT JOIN inquiries ON inquiries.ethnicity_id = options_ethnicity.ethnicity_id GROUP BY options_ethnicity.ethnicity_idUNION ALLSELECT   NULL Placeholder' AS ethnicity_name,    COUNT(inquiries.inquiry_id) AS count FROM inquiries WHERE inquiries.ethnicity_id IS NULL               
+ b% ]- i  [/ M4 w1 {    解决方案:
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则