基数违规:1222使用的SELECT语句具有不同的列数

时间:2014-04-27 23:07:14

标签: php mysql sql

为什么我收到此错误基数违规:1222使用的SELECT语句具有不同的列数

$query = "
SELECT DISTINCT s.studentid, s.fname, s.lname, s.studentcode, s.courseid, u.id 
FROM students as s,
courses as c, users as u, studentgrade as sg 
WHERE s.courseid = '$id' and u.id = (SELECT id FROM courses WHERE courseid = '$id') and u.id = (SELECT id FROM users WHERE username = '$nombre')
UNION ALL
SELECT SUM(sg.assignmentpoints) as sum
           FROM assignments as sg
           WHERE sg.courseid = 185
           GROUP BY sg.courseid
 ";

1 个答案:

答案 0 :(得分:1)

(
        SELECT DISTINCT s.studentid, s.fname, s.lname, s.studentcode, s.courseid, u.id 
        FROM students as s,
        courses as c, users as u, studentgrade as sg 
        WHERE s.courseid = '$id' and u.id = (SELECT id FROM courses WHERE courseid = '$id') and u.id = (SELECT id FROM users WHERE username = '$nombre')
)

- 查询A.

(
SELECT SUM(sg.assignmentpoints) as sum
           FROM assignments as sg
           WHERE sg.courseid = 185
           GROUP BY sg.courseid
)

- 查询B。

查询A应返回与请求B相同的列数。 所以在你的情况下:

SELECT DISTINCT s.studentid, s.fname, s.lname, s.studentcode, s.courseid, u.id 
FROM students as s,
courses as c, users as u, studentgrade as sg 
WHERE s.courseid = '$id' and u.id = (SELECT id FROM courses WHERE courseid = '$id') and u.id = (SELECT id FROM users WHERE username = '$nombre')
UNION ALL
SELECT SUM(sg.assignmentpoints) as sum, '', '', '', '', '', '', '', '', ''
           FROM assignments as sg
           WHERE sg.courseid = 185
           GROUP BY sg.courseid

我认为您需要Join,而不是Union

SELECT DISTINCT s.studentid, s.fname, s.lname, s.studentcode, s.courseid, u.id 
    FROM students as s,
    courses as c, users as u, studentgrade as sg 
    LEFT JOIN 
    (SELECT * 
    FROM assignments 
    GROUP BY courseid
    ) as asg on asg.courseid=s.courseid
    WHERE s.courseid = '$id' and u.id = (SELECT id FROM courses WHERE courseid = '$id') and u.id = (SELECT id FROM users WHERE username = '$nombre')