SQL在MySQL中使用JOIN来选择公共数据和剩余数据


SQL to select common as well as remaining data using JOIN in MySQL

我有三个表:wi_district, wi_group和wi_training。我需要根据地区来计算小组和培训。为此,我使用了以下SQL;

  • SQL1
<>之前选择wi_district。dst_name, COUNT(grp_id)为group_count, MAX(grp_created_date)为grp_created_date从wi_groupINNER JOIN wi_district ON wi_district.dst_id=wi_group。grp_dst_id AND wi_group。grp_deleted=0 AND wi_group。grp_type IN (3)GROUP BY wi_district.dst_name

每个地区的查询计数组。同样,

  • SQL2
<>之前选择wi_district。dst_name, COUNT(trn_id)作为training_count, MAX(trn_created_date)作为trn_created_date从wi_trainingINNER JOIN wi_district ON wi_district.dst_id=wi_training。dst_id AND wi_training。trn_deleted=0 AND wi_training。trn_beneficiary_type IN (-1,2,8,9,10)GROUP BY wi_district.dst_name

查询对每个地区的训练进行计数。现在我需要组合从SQL1和SQL2获得的所有结果,并以

的形式获得结果
dst_name || group_count || grp_created_date || training_count || trn_created_date

问题是每当我使用SQL1 LEFT JOIN SQL2时,它就会显示SQL1的结果,而SQL2的结果无法获得,反之亦然。请帮我解决MySQL中的这个问题

我认为您可以连接经过筛选的表,然后按地区名称分组。像这样:

SELECT dist.dst_name AS dst_name,
COUNT(grp.grp_id) AS group_count, MAX(grp.grp_created_date) AS grp_created_date,
COUNT(trn.trn_id) AS training_count, MAX(trn.trn_created_date) AS trn_created_date 
FROM wi_district AS dist
LEFT JOIN (
  SELECT dst_id, trn_id, trn_created_date
  FROM wi_training
  WHERE trn_deleted=0
    AND trn_beneficiary_type IN (-1,2,8,9,10)
) AS trn ON trn.dst_id=dist.dst_id
LEFT JOIN (
  SELECT grp_dst_id, grp_id, grp_created_date
  FROM wi_group
  WHERE grp_deleted=0
    AND grp_type IN (3)
) AS grp ON grp.grp_dst_id = dist.dst_id
GROUP BY dist.dst_name

为什么使用dst_name这样的名称?最好把全名写出来,这样几个月后你也能明白它的意思。

无论如何,这个查询应该能达到目的

select d.dst_name as district
,      count(distinct g.grp_id) as group_count
,      max(grp_created_date) as group_created_date 
,      count(distinct trn_id) as training_count
,      max(trn_created_date) as trn_created_date 
from   wi_district d
left join wi_group g on  d.dst_id = g.grp_dst_id
                     and g.grp_deleted = 0 
                     and g.grp_type in (3)
left join wi_training t on  d.dst_id = t.dst_id
                        and t.trn_deleted = 0
                        and t.trn_beneficiary_type IN (-1,2,8,9,10)
group by d.dst_name

您需要从分组表中DRIVE它。一样。

SELECT  D.dst_name,  COUNT(grp_id) AS group_count, MAX(grp_created_date) as grp_created_date, COUNT(trn_id) AS training_count, MAX(trn_created_date) as trn_created_date 
FROM    wi_district D
LEFT JOIN wi_group G ON D.dst_id = G.grp_dst_id AND G.grp_deleted=0 AND G.grp_type IN (3)
LEFT JOIN wi_training T ON  D.dst_id = T.dst_id AND T.trn_deleted=0 AND T.trn_beneficiary_type IN (-1,2,8,9,10)
GROUP BY wi_district.dst_name

如果您只需要在两个表上都存在的行,请添加子句:

WHERE NOT G.grp_dst_id IS NULL OR NOT D.dst_id IS NULL