我不明白。
此PHP-MYSQL查询确实有效:
$sql = mysqli_prepare($conn, 'SELECT O.*
FROM OFFER O
LEFT JOIN EVENT E ON E.OFFER_ID = O.KEY_ID
LEFT JOIN BOOKING B ON B.EVENT_ID = E.KEY_ID
WHERE O.KEY_ID = ? ');
$sql->bind_param('i', $keyId);
使用SUM语句不起作用:
$sql = mysqli_prepare($conn, 'SELECT O.*,
SUM(CASE WHEN B.KEY_ID IS NULL THEN 0 ELSE 1 END) AS BOOKING_COUNT
FROM OFFER O
LEFT JOIN EVENT E ON E.OFFER_ID = O.KEY_ID
LEFT JOIN BOOKING B ON B.EVENT_ID = E.KEY_ID
WHERE O.KEY_ID = ? ');
$sql->bind_param('i', $keyId);
错误消息: 未捕获的错误:在..snippet-ops.php(361)中以布尔值调用成员函数bind_param():eval()的代码:107
查询在phpmyadmin中有效,有人知道为什么吗?
编辑:已解决:接受的答案在注释中包含解决方案(打开报告并使用GROUP BY解决了该问题。
编辑2:降级问题时,最好知道为什么降级没有用。
答案 0 :(得分:1)
尝试用双引号而不是单引号引起来的查询字符串。请注意,prepare
可能会返回false
而不是语句对象。您应该检查并做出相应反应。完成之后,还请确保关闭您的声明。
此处(未测试):
<?php
$sql = "
SELECT O.*, SUM(CASE WHEN B.KEY_ID IS NULL THEN 0 ELSE 1 END) AS BOOKING_COUNT
FROM OFFER O
LEFT JOIN EVENT E ON E.OFFER_ID = O.KEY_ID
LEFT JOIN BOOKING B ON B.EVENT_ID = E.KEY_ID
WHERE O.KEY_ID = ?
GROUP BY O.KEY_ID";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("i", $keyId);
$stmt->execute();
// do stuff with $stmt
$stmt->close();
} else {
echo $stmt->error;
}
?>
更新:从注释中可以看出,有必要对O.KEY_ID列进行分组,否则prepare
将返回false
。