[英]SQL query works fine when testing through phpmyadmin but fails when attempting the same thing in PHP PDO
好的,從另一個用戶的問題上,我有以下查詢:
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語句中設置變量?
同樣,它不是設置變量,而是它試圖同時運行兩個查詢的問題。 所以我需要將上面的代碼更改為此:
$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;
}
那兩個查詢
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;
可以被當作一個查詢,所以只需要一個prepere語句
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.