2013-04-07 60 views
0

我有兩個SQL查詢SQL查詢 - 我的查詢需要哪種類型的JOIN?

第一次查詢:我得到除日,所有細節相關細節

SELECT att.roll_no AS `att_roll_no`,att.full_name,att.st_class,att.st_section, 
SUM(att.hasAttended= 'P') AS DaysPresent, 
SUM(att.hasAttended= 'A') AS DaysAbsent, 
COUNT(DISTINCT att.att_date) AS WorkingDays, 
COUNT(*) AS totalClasses 
FROM  attendance as att 
WHERE att.st_class = 1 AND att.st_section = 'A' 
GROUP BY att.roll_no 

上面查詢的輸出表如下:

enter image description here

第二次查詢:我只收到日期相關的詳細信息

SELECT hasAttended, att_date FROM attendance 
WHERE st_class = 1 AND st_section = 'A' AND att_date = 'Tue Apr 02 2013' 
GROUP BY roll_no 

上面查詢的輸出表如下:

enter image description here

現在我需要將以上兩個表連爲一體的表。

我曾嘗試

在我使用INNER JOIN生成的查詢。它如下:

SELECT 
    att_outer.hasAttended, 
    att_outer.att_date 
FROM 
    attendance AS att_outer 
    INNER JOIN(
    SELECT 
     att.roll_no AS `att_roll_no`, 
     att.full_name, 
     att.st_class,att.st_section, 
     SUM(att.hasAttended= 'P') AS DaysPresent, 
     SUM(att.hasAttended= 'A') AS DaysAbsent, 
     COUNT(DISTINCT att.att_date) AS WorkingDays, 
     COUNT(*) AS totalClasses 
    FROM 
     attendance as att 
    WHERE 
     att.st_class = 1 
     AND att.st_section = 'A' 
    GROUP BY att.roll_no 
)att ON att_outer.roll_no = att.roll_no 
WHERE 
    att_outer.st_class = 1 
    AND att_outer.st_section = 'A' 
    AND att_outer.att_date = 'Tue Apr 02 2013' 
GROUP BY roll_no 

但我收到以下錯誤:

#1054 - Unknown column 'att.roll_no' in 'on clause' 

請讓我知道結果查詢是否正確與否。也加入我使用的是否正確。

謝謝。

回答

1

你已經在你的內心提供該列的別名查詢。您應該使用該別名,因爲該列不再可見。

SELECT att_outer.hasAttended, 
     att_outer.att_date, 
     att.full_name, 
     att.st_class, 
     att.st_section, 
     att.DaysPresent, 
     att.DaysAbsent, 
     att.WorkingDays, 
     att.totalClasses 
FROM attendance AS att_outer 
     INNER JOIN 
     (
      SELECT att.roll_no AS `att_roll_no`, 
        att.full_name, 
        att.st_class, 
        att.st_section, 
        SUM(att.hasAttended= 'P') AS DaysPresent, 
        SUM(att.hasAttended= 'A') AS DaysAbsent, 
        COUNT(DISTINCT att.att_date) AS WorkingDays, 
        COUNT(*) AS totalClasses 
      FROM attendance as att 
      WHERE att.st_class = 1 AND 
        att.st_section = 'A' 
      GROUP BY att.roll_no 
     )att ON att_outer.roll_no = att.att_roll_no 
WHERE att_outer.st_class = 1 AND 
     att_outer.st_section = 'A' AND 
     att_outer.att_date = 'Tue Apr 02 2013' 
+0

好的感謝指出,但在我的結果表中,我只得到我的外表的行。 。我需要我的內表的行以及... – NealCaffrey 2013-04-07 12:42:10

+1

看到我更新的答案。你還沒有預測到它。還刪除了「GROUP BY」子句。 – 2013-04-07 12:44:18

+0

非常感謝您的回答!這是完美的 !! :-) – NealCaffrey 2013-04-07 12:49:18

1

您在select子句中沒有名爲roll_no的列,因此您無法對此進行連接,因此錯誤:att.roll_no。

2

你想加入的別名來代替,別名爲att_roll_no

變化:

ON att_outer.roll_no = att.roll_no 

ON att_outer.roll_no = att_roll_no 
+0

噢好的謝謝我糾正了..但現在在我的結果表中,我只得到我外表table.i.e的行。只有兩行 - att_outer.hasAttended,att_outer.att_date ..我需要我的內部表的所有行以及... – NealCaffrey 2013-04-07 12:43:30