0

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

我有 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        |
---------------------------------------------------------

并且已经完成了 75% 的类型 1(即我发现它是这样的

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

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

4

2 回答 2

0

似乎这已经完成并且除尘了,但是如何...

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;
于 2013-05-07T12:39:00.303 回答
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

“表 1 中的学生 ID 没有错过任何类型 3”......我在这里假设您不想包括没有任何类型 3 行的学生。

于 2013-05-07T10:31:39.780 回答