如何将所选查询作为别名用于另一个子查询?

jvidinwx  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(345)

我试图为我的问题找到答案,但找不到适合我的答案。例如,我有两个表,分别是学生表和测试表。students有两个字段student\u id,name和for tests,test\u id和student\u id。我要做的是查询打印student\u id,name和学生完成的总测试。我失败的查询是

SELECT S.student_id, T.TOTAL 
FROM students as S , ((SELECT student_id, COUNT(test_id) AS TOTAL
FROM tests
GROUP BY student_id) AS T)
WHERE S.student_id = T.student_id;

它回来了
第1行出现错误1064(42000):您的sql语法有错误;检查与mysql服务器版本相对应的手册,了解第2行中使用“as t”附近的正确语法
如何将alias selected查询设置为“临时表”,以便在另一个子查询中使用?请给我最简单的答案,也在mysql高级答案,这样我可以比较这两个答案,以供以后研究。谢谢您

6ss1mwsb

6ss1mwsb1#

没有真正不同的逗号分隔和写连接显式。我更喜欢显式地编写连接,因为有不同的连接类型。
带显式连接

SELECT S.student_id, T.TOTAL 
FROM students AS S
INNER JOIN (
    SELECT student_id, COUNT(test_id) AS TOTAL
    FROM tests GROUP BY student_id
) AS T ON S.student_id = T.student_id;

在选择

SELECT S.student_id, (SELECT COUNT(test_id) AS TOTAL
FROM tests
where tests.student_id = S.student_id
GROUP BY student_id) as Total
FROM students AS S;

顺其自然(从子查询中删除多余的大括号)

SELECT S.student_id, T.TOTAL 
FROM students AS S , (SELECT student_id, COUNT(test_id) AS TOTAL
FROM tests
GROUP BY student_id) AS T
WHERE S.student_id = T.student_id;

示例

相关问题