我对此代码感到困惑,我已经在mysql上创建了存储过程这是我的存储过程代码
CREATE DEFINER=`root`@`localhost` PROCEDURE `getChats`(
IN `idUser` VARCHAR(50)
)
LANGUAGE SQL
NOT DETERMINISTIC
READS SQL DATA
SQL SECURITY DEFINER
COMMENT ''
BEGIN
SET @sqlQuery = 'SELECT user.id AS owner_id, user.name, user.image, chats.sender, chats.recipient, chats.date_sent, chats.content FROM chats
INNER JOIN (
SELECT MAX( id_chat ) AS id_chat
FROM chats AS alt
WHERE alt.recipient = ?
OR alt.sender = ?
GROUP BY LEAST(recipient, sender), greatest(recipient, sender)
) AS chat ON chats.id_chat = chat.id_chat
INNER JOIN user ON user.id = CASE WHEN chats.sender = ?
THEN chats.recipient
ELSE chats.sender
END';
PREPARE sqlQuery FROM @sqlQuery;
execute sqlQuery using @idUser, @idUser, @idUser;
END
这是CALL getChats('USER15703082085d99007096571')
的结果
[https://puu.sh/EpRhZ.png来自Heidi SQL的结果
[https://puu.sh/EpRmz.png来自phpmyadmin的结果
[https://puu.sh/EpRub.png来自php pdo的结果
我的PHP代码
$conn = new PDO(sprintf("mysql:host=%s;dbname=%s", "localhost", "kosan_finder"), "root", "");
$sql = "CALL getChats(?)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, $PostData->sender);
$stmt->execute();
echo "Result stmt: ";
print_r($stmt->fetchAll(PDO::FETCH_ASSOC));
echo "\nError info: ";
print_r($stmt->errorInfo());
我需要的是我可以在PHP上获取数据
无需在存储过程中使用动态SQL。另外,过程参数可以原样使用(而不是@param)。
使用正确参数的代码如下:
CREATE DEFINER=`root`@`localhost` PROCEDURE `getChats`(
idUser VARCHAR(50)
)
BEGIN
SELECT user.id AS owner_id, user.name, user.image, chats.sender, chats.recipient, chats.date_sent, chats.content
FROM chats INNER JOIN (
SELECT MAX( id_chat ) AS id_chat
FROM chats AS alt
WHERE alt.recipient = idUser OR alt.sender = idUser
GROUP BY LEAST(recipient, sender), greatest(recipient, sender)
) AS chat ON chats.id_chat = chat.id_chat
INNER JOIN user ON user.id =
CASE WHEN chats.sender = idUser
THEN chats.recipient
ELSE chats.sender
END;
END
在查询中使用GROUP BY
看起来很奇怪。不知道您要怎么做。