我想基于三个表显示这样的摘要

时间:2018-11-11 11:44:31

标签: php mysql sql mysqli

我的3个MYSQL表如下:

表1:公民

=============================
ID |  Name | Sex    | Address |
=============================
5  | James | Male   | India
6  | Shella|Female  | India
7  | Jan   | Male   | NY
8  | May   | Female | USA
==============================

表2:好处

========================== 
ID| benefits
==========================
1 | SSS
2 | Coco Life
3 | PhiHealth
4 | Sunlife
==========================

表3:养老金领取者

============================
ID| benefits_ID | citizen_ID
============================
1 | 1           | 5
2 | 2           | 6
3 | 1           | 7
4 | 4           | 7
==========================

我想显示如下:

====================================================================
Address | Total Citizen | Male | Female | SSS | Coco Life | Others |
====================================================================
India   | 2             |  1   |  1     |  1  |    1      |   0    |
NY      | 1             |  1   |  0     |  1  |    0      |   1    |
USA     | 1             |  0   |  1     |  0  |    0      |   0    | 
==================================================================

任何人都可以给我提示如何做吗?

1 个答案:

答案 0 :(得分:1)

您可以使用适当的关系通过Left Join表从Address表到benefits表进行pensioners。即使没有任何公民的相应Address条目,左联接也使我们可以考虑使用benefits

要计算公民总数,男性人数和女性人数,您现在需要在加入后使用COUNT(DISTINCT ID)。由于加入可能会创建重复的行,因此作为公民可能会获得多个好处。

此外,为了计算“其他”收益,我们需要确保benefit IS NOT NULL确实是NOT IN ('SSS', 'Coco Life')

在多表查询中,建议使用Aliasing来提高代码的清晰度(可读性)并避免模棱两可的行为。

SELECT  
  c.Address,
  COUNT(DISTINCT CASE WHEN c.Sex = 'Male' THEN c.ID END) AS male_cnt,
  COUNT(DISTINCT CASE WHEN c.Sex = 'Female' THEN c.ID END) AS female_cnt,
  COUNT(DISTINCT c.ID) AS total_citizen_cnt, 
  COUNT(CASE WHEN b.benefits = 'SSS' THEN 1 END) AS SSS_cnt, 
  COUNT(CASE WHEN b.benefits = 'Coco Life' THEN 1 END) AS Coco_Life_cnt, 
  COUNT(CASE WHEN b.benefits IS NOT NULL AND 
                  b.benefits NOT IN ('SSS', 'Coco Life') THEN 1 END) AS Others_cnt 
FROM citizen AS c 
LEFT JOIN pensioners AS p
  ON p.citizen_ID = c.ID 
LEFT JOIN benefits AS b 
  ON b.ID = p.benefits_ID 
GROUP BY c.Address