2013-04-07 72 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