将另一个表添加到SQL结果中

时间:2017-01-14 22:34:37

标签: mysql sql

我正在解决这个问题。我正在尝试将另一个表中的数据添加到现有的sql查询中:

Table Alfa (AA, AB, AC)


Table Zulu (ZA, ZB)

我现有的查询:

SELECT AB
     , ROUND(AVG(AC),0) AS Srednia
     , COUNT(AC) AS Uzyt 
  FROM Alfa 
 WHERE AA = %s 
 GROUP 
    BY AB 
 ORDER 
    BY AB ASC

如果ZA = AB,如何将ZB添加到结果中?

2 个答案:

答案 0 :(得分:3)

这是你的意思吗?

SELECT a.AB, ROUND(AVG(a.AC),0) AS Srednia, COUNT(a.AC) AS Uzyt, Z.ZB FROM Alfa A 
INNER JOIN Zulu Z ON A.AB = Z.ZA
WHERE A.AA = %s
GROUP BY A.AB ORDER BY A.AB ASC

答案 1 :(得分:0)

您将子查询放在from子句中作为派生表:

SELECT
  a.AB,
  a.Srednia,
  a.Uzyt,
  z.ZB
FROM
(
  SELECT AB
       , ROUND(AVG(AC),0) AS Srednia
       , COUNT(AC) AS Uzyt 
    FROM Alfa 
   WHERE AA = %s 
   GROUP BY AB 
) a
JOIN Zulu z ON z.ZA = a.AB
ORDER BY a.AB ASC;