SQL使用MySQL中的JOIN选择常用数据和剩余数据

时间:2014-06-19 14:13:08

标签: php mysql sql join

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

  • SQL1
SELECT wi_district.dst_name, COUNT(grp_id) AS group_count, MAX(grp_created_date) as grp_created_date 
FROM wi_group 
INNER 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
SELECT wi_district.dst_name, COUNT(trn_id) AS training_count, MAX(trn_created_date) as trn_created_date 
FROM wi_training 
INNER 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中的这个问题

3 个答案:

答案 0 :(得分:0)

我认为您可以加入已过滤的表格,然后按地区名称进行分组。像这样:

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

答案 1 :(得分:0)

为什么要使用像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

答案 2 :(得分:0)

您需要从分组表中将其驱动。像这样。

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