7

您好我需要通过加入两个查询来生成一个 sql 查询

第一个查询:获取所有学生数据

SELECT * FROM students where class = 1 and section = 'A'

在此处输入图像描述

第二个查询:获取每个出席人数

SELECT  roll_no,full_name, 

SUM(hasAttended= 'P') AS DaysPresent, 

SUM(hasAttended= 'A') AS DaysAbsent, 

COUNT(*) AS totalClasses

FROM     attendance

GROUP BY roll_no

在此处输入图像描述

现在我需要加入这两个表并生成一个结果表

我正在尝试以下查询,但出现错误:

1248 - 每个派生表都必须有自己的别名

我的查询如下:

SELECT * FROM students as st

INNER JOIN 

(SELECT  att.roll_no,att.full_name, 

SUM(att.hasAttended= 'P') AS DaysPresent, 

SUM(att.hasAttended= 'A') AS DaysAbsent, 

COUNT(*) AS totalClasses

FROM     attendance as att

GROUP BY att.roll_no)

ON st.roll_no = att.roll_no

ORDER BY  st.roll_no

有人可以解决上述错误吗

4

2 回答 2

14

MySQL 要求所有派生表和子查询都有一个别名。您在 subqquery 的右括号末尾缺少别名:

SELECT * 
FROM students as st
INNER JOIN 
(
  SELECT  att.roll_no,att.full_name, 
    SUM(att.hasAttended= 'P') AS DaysPresent, 
    SUM(att.hasAttended= 'A') AS DaysAbsent, 
    COUNT(*) AS totalClasses
  FROM     attendance as att
  GROUP BY att.roll_no
) att  ---------------------------< this is missing
  ON st.roll_no = att.roll_no
WHERE st.class = 1 
ORDER BY  st.roll_no
于 2013-04-03T11:22:54.547 回答
0

一般 subqquery 需要一个别名如上。我也有一个问题已经解决了。你可以看到我解决的查询。IE

SELECT SUM(total_items) AS sum_total
FROM 
(SELECT COUNT(imt.item_id) AS total_items
    FROM item_master_tbl imt
    INNER JOIN map_category_item_tbl mci 
                ON imt.item_id=mci.item_id
    INNER JOIN category_master_tbl cmt 
                ON mci.category_id=cmt.category_id
    GROUP BY cmt.category_id) alias_name;
于 2013-08-27T12:50:12.073 回答