好的here上的其他用户问题我有以下问题:
set @test = 0, @id=0, @count=0;
select m.id, max(count)
from (
select
@count := if(TookTest = 1 and PatientID = @id, @count+1, 0) as count,
@test := Tooktest,
@id := PatientID as id
from medical) as m
group by m.id
having max(count) >=2;
这在phpmyadmin中运行正常,但是当我在PDO语句中尝试相同时,它会失败并显示以下错误消息:
PDOException:SQLSTATE [HY000]:常规错误
$sql="set @test = 0, @id=0, @count=0;
select m.id, max(count)
from (
select
@count := if(TookTest = 1 and PatientID = @id, @count+1, 0) as count,
@test := Tooktest,
@id := PatientID as id
from medical) as m
group by m.id
having max(count) >=2;";
try{
$stmt=$dbh->prepare($sql);
if ($stmt->execute()){
$rows=$stmt->fetchall();
}
}catch(PDOException $s){
echo $s;
}
我是否缺少这样的东西,就像你无法在PDO语句中设置变量一样?
答案 0 :(得分:1)
同样,它不是设置变量,而是它试图同时运行两个查询的问题。所以我需要将上面的代码更改为:
$sql="set @test = 0, @id=0, @count=0;";
try{
$stmt=$dbh->prepare($sql);
$stmt->execute()
}catch(PDOException $s){
echo $s;
}
$sql="select m.id, max(count)
from (
select
@count := if(TookTest = 1 and PatientID = @id, @count+1, 0) as count,
@test := Tooktest,
@id := PatientID as id
from medical) as m
group by m.id
having max(count) >=2;";
try{
$stmt=$dbh->prepare($sql);
if ($stmt->execute()){
$rows=$stmt->fetchall();
}
}catch(PDOException $s){
echo $s;
}
答案 1 :(得分:1)
这两个查询
set @test = 0, @id=0, @count=0;
select m.id, max(count)
from (
select
@count := if(TookTest = 1 and PatientID = @id, @count+1, 0) as count,
@test := Tooktest,
@id := PatientID as id
from medical) as m
group by m.id
having max(count) >=2;
可以重新命名为一个查询,因此您只需要一个预备语句
select m.id, max(count)
from (
select
@count := if(TookTest = 1 and PatientID = @id, @count+1, 0) as count,
@test := Tooktest,
@id := PatientID as id
from medical) as m
cross join ( select @test := 0, @id := 0, @count = :0 ) as init_user_params
group by m.id
having max(count) >=2;