我有以下SQL查询,并且我尝试实现分页,所以我首先要获得结果的COUNT:
正常查询(工作正常)
SELECT DISTINCT c.*, p1.*, username FROM candidate c
LEFT JOIN note p1 ON (c.candID = p1.candidateID)
LEFT JOIN user ON p1.userID = user.id
LEFT OUTER JOIN note p2 ON
(c.candID = p2.candidateID AND (p1.noteID < p2.noteID))
WHERE p2.candidateID IS NULL ORDER BY c.firstname ASC
我已经尝试了以下操作,但它会抛出错误,我不确定要使用哪种正确的语法:
尝试计算结果(不起作用)
SELECT COUNT(DISTINCT c.*, p1.*, username) FROM candidate c
LEFT JOIN note p1 ON (c.candID = p1.candidateID)
LEFT JOIN user ON p1.userID = user.id
LEFT OUTER JOIN note p2 ON
(c.candID = p2.candidateID AND (p1.noteID < p2.noteID))
WHERE p2.candidateID IS NULL ORDER BY c.firstname ASC
错误:
语法错误或访问冲突:1064您的SQL语法出错;检查与您的MySQL服务器版本相对应的手册,以便在<&#39; ,p1。,用户名)附近使用正确的语法。来自候选人c LEFT&#39;第1行
答案 0 :(得分:2)
一种选择是使用子查询:
SELECT COUNT(*)
FROM (
SELECT DISTINCT c.*, p1.*, username FROM candidate c
LEFT JOIN note p1 ON (c.candID = p1.candidateID)
LEFT JOIN user ON p1.userID = user.id
LEFT OUTER JOIN note p2 ON
(c.candID = p2.candidateID AND (p1.noteID < p2.noteID))
WHERE p2.candidateID IS NULL
) t
根据您的数据,您可以在没有子查询的情况下执行此操作,但不能将多列与count
聚合一起使用 - 这是造成错误的原因。