如何加入两个SELECT语句?

时间:2015-08-05 04:28:50

标签: mysql select

SELECT fullname,
SUM(IF(mark='c',1,0)) AS compensations,
ROUND(AVG(mark)) AS avg_mark
FROM evaluation
WHERE subject='$subject' AND fullname IN
(SELECT fullname
FROM campus
WHERE user_levels=1)
GROUP BY fullname ASC


SELECT fullname,
SUM(IF(attend='a',1,0)) AS absences
FROM attendance 
WHERE subject='subject I' AND fullname IN
(SELECT fullname FROM campus WHERE user_levels=1) 
GROUP BY fullname ASC

我需要为每个符合陈述的学生展示:fullname,avg_mark,补偿和平均值。

这两个代码本身非常出色,但我似乎无法将它们组合在一起。拜托,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

那些表确实很奇怪。为什么要在3个不同的表中存储全名?看起来不对劲。

另外:

  • 优先使用INNER JOIN IN(...)
  • 建议在IF()函数上使用case表达式

但是,我认为以下内容可能有效:

SELECT
      c.fullname
    , SUM(CASE
            WHEN e.mark = 'c' THEN 1
            ELSE 0
      END) AS compensations
    , ROUND(AVG(e.mark)) AS avg_mark
    , SUM(CASE
            WHEN a.attend = 'a' THEN 1
            ELSE 0
      END) AS absences
FROM campus c
LEFT JOIN evaluation e
      ON c.fullname = e.fullname
      AND e.subject = '$subject'
LEFT JOIN attendance a
      ON c.fullname = a.fullname
      AND a.subject = 'subject I'
WHERE c.user_levels = 1
GROUP BY c.fullname
;