gpt4 book ai didi

php - 如何获取左连接 mySQL 表的 id?

转载 作者:行者123 更新时间:2023-11-29 10:54:15 25 4
gpt4 key购买 nike

像这样,我的 mySQL 请求运行良好:

 <?php
$id = 12;

$pdo = $db->prepare("
SELECT *,
horse.id AS h
FROM dog
LEFT JOIN cat ON dog.name=cat.name
LEFT JOIN horse ON dog.name=horse.name
WHERE animal = ?");
$pdo->execute(array($id));
$animals = $pdo->fetchAll();

foreach ($animals as $row) {
echo $row["h"];
}
?>

但是如果我想获取dog.id...

 <?php

$id = 12;

$pdo = $db->prepare("
SELECT *,
horse.id AS h
dog.id AS d
FROM dog
LEFT JOIN cat ON dog.name=cat.name
LEFT JOIN horse ON dog.name=horse.name
WHERE animal = ?");
$pdo->execute(array($id));
$animals = $pdo->fetchAll();

foreach ($animals as $row) {
echo $row["h"];
echo $row["d"];
}
?>

...有错误:

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'dog.id AS d FROM dog LEFT JOIN cat ON dog.name=cat.name' at line 3 in /myproject.php:31 Stack trace: #0 /myproject.php(31): PDOStatement->execute(Array) #1 {main} thrown in /myproject.php on line 31

最佳答案

根据您的数据和错误消息,您在查询中在 horse.id AS h 之后漏掉了一个逗号,它应该是

SELECT *,
horse.id AS h,
dog.id AS d
FROM dog
LEFT JOIN cat ON dog.name=cat.name
LEFT JOIN horse ON dog.name=horse.name

关于php - 如何获取左连接 mySQL 表的 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43259511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com