查询MySQL Group by和Having

时间:2013-05-07 10:07:30

标签: mysql sql

我正在为我的学校创建一个应用程序,我在构建正确的查询时遇到了麻烦。

我有2个表,table1和table2。

表1

---------------------------------------------------------
| StudentID  | SubjectID   | Present        | Type      |
---------------------------------------------------------
| 2          | 3           | yes            |  1        |
| 2          | 2           | yes            |  2        |
| 3          | 1           | no             |  3        |
---------------------------------------------------------

表2

---------------------------------------------------------
| SubjectID  | SubjectName | Number1        | Number2   |
---------------------------------------------------------
| 1          | Name1       | 6              |  4        |
| 2          | Name2       | 4              |  8        |
| 3          | Name3       | 5              |  2        |
---------------------------------------------------------

table1中的SubjectID是外键引用table2。

我想构建一个查询sql,它从table1给我一个StudentID 没有错过任何第3类主题(即没有像这样的行

---------------------------------------------------------
| StudentID  | SubjectID   | Present        | Type      |
---------------------------------------------------------
| 3          | 1           | no             |  3        |
---------------------------------------------------------

完成了第1类的75%(即 我发现它就像这样

SELECT t1.StudentID,t1.SubjectID ,t1.Type,t2.Number1 as num
FROM table1 as t1,table2 as t2
WHERE t1.Present=yes and t2.SubjectID=t1.SubjectID
GROUP BY StudentID,SubjectID
HAVING COUNT(*)/num >= 75/100

但我不能将这两件事结合在一起。

2 个答案:

答案 0 :(得分:0)

您可以通过为查询提供别名并作为子查询加入来组合查询...

SELECT finisher.StudentID FROM
(
    SELECT DISTINCT StudentID
    FROM table1 t1
    JOIN table2 t2 ON t2.SubjectID = t1.SubjectID
    WHERE t1.Present = 'yes' AND t1.Type1 = 1
    GROUP BY t1.StudentID, t2.SubjectID
    HAVING COUNT(*) / t2.Number2 >= 0.75
) finisher
JOIN
(
    SELECT DISTINCT t1.StudentID
    FROM table1 t1
    LEFT JOIN
    ( 
        SELECT DISTINCT StudentID 
        FROM table1 
        WHERE Type = 3 AND Present = 'no'
    ) missed ON missed.StudentID = t1.StudentID
    WHERE t1.Type = 3
    AND missed.StudentID IS NULL
) notmissed ON finisher.StudentID = notmissed.StudentID

“来自table1的StudentID'并没有错过任何类型3”...我在这里假设您不想包含没有任何类型3行的学生。

答案 1 :(得分:0)

似乎已经完成并且duste,但是怎么样......

SELECT x.*
  FROM
     ( SELECT t1.StudentID
            , t1.SubjectID 
            , t1.Type
            , t2.Number1 num
         FROM table1 t1
         JOIN table2 t2   
           ON t2.SubjectID=t1.SubjectID
        WHERE t1.Present='yes' 
        GROUP 
           BY t1.StudentID
            , t1.SubjectID
       HAVING COUNT(*)/num >= 0.75
     ) x
  LEFT
  JOIN table1 y
    ON y.student_id = x.student_id
   AND y.subject_id = x.subject_id
   AND y.type = 3
   AND y.present = 'no'
 WHERE y.student_id IS NULL;