SQL查询 - 我的查询需要哪种类型的JOIN?

时间:2013-04-07 12:34:30

标签: mysql join

我有两个SQL查询

第一次查询:我收到除日期相关细节之外的所有细节

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'

请告诉我生成的查询是否正确。加入我正在使用是否正确。

感谢。

3 个答案:

答案 0 :(得分:2)

您希望加入ALIAS名称,别名为att_roll_no

变化:

 ON att_outer.roll_no = att.roll_no

ON att_outer.roll_no = att_roll_no

答案 1 :(得分:1)

在select子句中没有名为roll_no的列,因此您无法对此进行连接,从而导致错误:att.roll_no。

答案 2 :(得分: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'