Php SQL在MySQL中使用JOIN选择公共数据和剩余数据
我有三张桌子:wi_区、wi_集团和wi_培训。我需要根据地区统计小组和培训。为此,我使用了以下SQL SQL1 查询统计每个地区的组数。同样地 SQL2 该查询统计每个地区的培训。现在我需要组合从SQL1和SQL2获得的所有结果,并以 dst_name || group_count || grp_created_date || training_count || trn_created_datePhp SQL在MySQL中使用JOIN选择公共数据和剩余数据,php,mysql,sql,join,Php,Mysql,Sql,Join,我有三张桌子:wi_区、wi_集团和wi_培训。我需要根据地区统计小组和培训。为此,我使用了以下SQL SQL1 查询统计每个地区的组数。同样地 SQL2 该查询统计每个地区的培训。现在我需要组合从SQL1和SQL2获得的所有结果,并以 dst_name || group_count || grp_created_date || training_count || trn_created_date 问题是,每当我使用SQL1左连接SQL2时,它都会显示与SQL1对应的结果,其中无法获得SQL2的
问题是,每当我使用SQL1左连接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
您需要从分组表中驱动它。像这样
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
然后不要使用左连接。左联接是左表中的所有匹配记录,右表中的任何匹配记录。如果您需要两个表中的所有记录,则需要外部联接。不客气。只需确保计数中包含DISTINCT关键字,否则组计数将与每个地区的培训数相乘。如果是答案,则将其标记为答案:
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