如何将三个多个sql查询组合成一个输出

时间:2015-10-26 13:09:15

标签: mysql left-join inner-join

我正在尝试将下面的sql查询组合起来以获得单个输出

SELECT reg.REGION_ID, count(*) as totalDist FROM REGION reg LEFT OUTER JOIN ORGANIZATION org
ON org.FK_REGION=reg.REGION_ID group by reg.REGION_ID;

SELECT reg.REGION_ID, count(*) as activeTotal FROM REGION reg LEFT OUTER JOIN ORGANIZATION org
ON org.FK_REGION=reg.REGION_ID and org.ACTIVE=1 group by reg.REGION_ID;

select u.Region_ID, count(*) as userCount from USER u where u.ORG_ID IN(
 Select org.ORG_ID from ORGANIZATION org where org.FK_REGION IN(select REGION_ID from REGION reg))  group by ORG_ID;

1 个答案:

答案 0 :(得分:0)

在它们之间添加SELECT reg.REGION_ID, COUNT(*) AS totalDist FROM REGION reg LEFT OUTER JOIN ORGANIZATION org ON org.FK_REGION=reg.REGION_ID GROUP BY reg.REGION_ID UNION SELECT reg.REGION_ID, COUNT(*) FROM REGION reg LEFT OUTER JOIN ORGANIZATION org ON org.FK_REGION=reg.REGION_ID AND org.ACTIVE=1 GROUP BY reg.REGION_ID UNION SELECT u.Region_ID, COUNT(*) FROM `USER` u WHERE u.ORG_ID IN(SELECT org.ORG_ID FROM ORGANIZATION org WHERE org.FK_REGION IN(SELECT REGION_ID FROM REGION reg)) GROUP BY ORG_ID;

SELECT r.REGION_ID, s1.totalDist, s2.activeTotal, s3.useCount
FROM REGION r
LEFT JOIN 
(
  SELECT reg.REGION_ID, COUNT(*) AS totalDist
  FROM REGION reg 
  LEFT OUTER JOIN ORGANIZATION org
   ON org.FK_REGION=reg.REGION_ID 
  GROUP BY reg.REGION_ID
) AS s1
 ON r.REGION_ID = s1.REGION_ID
LEFT JOIN
(
  SELECT reg.REGION_ID, COUNT(*) AS activeTotal
  FROM REGION reg
  LEFT OUTER JOIN ORGANIZATION org
    ON org.FK_REGION=reg.REGION_ID 
   AND org.ACTIVE=1
  GROUP BY reg.REGION_ID
) AS s2
  ON r.REGION_ID = s2.REGION_ID
LEFT JOIN
(
  SELECT u.Region_ID, COUNT(*) AS  useCount 
  FROM `USER` u
  WHERE u.ORG_ID IN(SELECT org.ORG_ID 
                  FROM ORGANIZATION org
                  WHERE org.FK_REGION IN(SELECT REGION_ID FROM REGION reg))
) AS s3
  ON r.REGION_ID = s3.REGION_ID;

修改

for (Int starting = Integer.parseInt(Start.getText()); starting =< ending; starting++){

Output.setText(starting);

}