mysql 使用 JOIN 与 PDO 请求不明确

问题描述 投票:0回答:1

在mysql/phpmyadmin中运行以下语句成功:

SELECT longitude,latitude FROM event JOIN location ON event.locationId=location.id WHERE 
event.id=1234

在 php 8.1 中使用 PDO 运行它,它说“id”在 where 子句中不明确..

SELECT longitude,latitude FROM event JOIN location ON event.locationId=location.id WHERE 
event.id=:event-id

$stmt->execute([':event-id' => 1234]);

Select failed: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous

有什么想法为什么它不能使用已经完全限定的表名吗?

提前致谢 罗伯特

php mysql pdo
1个回答
0
投票

您不能使用

-
作为 PDO 参数占位符的一部分。

PDO 认为占位符名称是

:event
,其余部分是 SQL 的一部分 - 因此,如果您的事件 ID 是
1234
,最终查询将最终为

SELECT longitude,latitude FROM event JOIN location ON event.locationId=location.id WHERE 
event.id=1234-id

即它会尝试从值

id
中减去
1234
的值 - 当然,此时
id
是不明确的,因为不清楚您指的是哪个表。

你需要写一些类似的东西。

SELECT longitude,latitude FROM event JOIN location ON event.locationId=location.id WHERE 
event.id=:eventID

$stmt->execute([':eventID' => 1234]);

问题演示:https://phpize.online/sql/mysql57/f2c28fcc3cddb7cc6dd3e41c9103be06/php/php81/d2d6ad622855fb0f5c9e89e0a4bdf2be/

修复演示:https://phpize.online/sql/mysql57/f2c28fcc3cddb7cc6dd3e41c9103be06/php/php81/08a62284d24eb04be2e96e36373b3412/

© www.soinside.com 2019 - 2024. All rights reserved.