将具有不同模式的两个SELECT语句中的“生成”结果连接到一个表中

时间:2011-11-12 17:26:43

标签: mysql sql postgresql

所以我有以下SELECT语句:

SELECT COUNT(A.Award) AS US, SUBSTRING(CAST(M.Year as char(4)), 0 , 4)  AS Decade
FROM Movies M, Awards A
WHERE {SOME WHERE CLAUSE}
GROUP BY Decade;

SELECT COUNT(*) AS Total, SUBSTRING(CAST(A2.Year as char(4)), 0 , 4) AS Decade
FROM Awards A2
WHERE {SOME WHERE CLAUSE}
GROUP BY Decade;

第一个是“生成”带有列的表( US Decade ),第二个是“生成”另一个带有列的表( Total 十年)。我想加入这两个表,以便我得到一个表( US Total Decade )。我该怎么办?

1 个答案:

答案 0 :(得分:21)

将它们放在子查询中并执行JOIN

SELECT a.US, a.decade, b.total FROM

  (SELECT COUNT(A.Award) AS US, SUBSTRING(CAST(M.Year as char(4)), 0 , 4)  AS Decade
  FROM Movies M, Awards A
  WHERE {SOME WHERE CLAUSE}
  GROUP BY Decade ) AS a

INNER JOIN

  (SELECT COUNT(*) AS Total, SUBSTRING(CAST(A2.Year as char(4)), 0 , 4) AS Decade
  FROM Awards A2
  WHERE {SOME WHERE CLAUSE}
  GROUP BY Decade) AS b

ON a.decade = b.decade