select COUNT(q1) as 'result'
from (select DISTINCT id_qs as 'q1' FROM main where id_exam=40) as q2
这是查询完美的工作。但。当我把它放在PHP代码中时:
function HowManyQuestion($id)
{
mysql_connect($this->hostname,$this->username,$this->password) OR DIE("Can't connect");
mysql_select_db($this->dbName) or die(mysql_error());
$query = "select COUNT(q1) as 'result' from (select DISTINCT id_qs as 'q1' FROM main where id_exam=40) as q2;";
$res = mysql_query($query) or die(mysql_error());
$id=0;
while ($row=mysql_fetch_array($res)) {
$id=$row['result'];
break;
}
return $id;
}
结果我有错误:
您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在第1行附近使用正确的语法作为q2'
那怎么修复?
答案 0 :(得分:5)
实际上,您可以在不使用子查询的情况下简化查询,而我认为将删除错误。
SELECT COUNT(DISTINCT id_qs) totalCount
FROM main
WHERE id_exam = 40
答案 1 :(得分:0)
别名列名称不能用于进一步处理
select COUNT(id_qs) as 'result'
from (select DISTINCT id_qs as 'q1' FROM main where id_exam=40) as q2