简体   繁体   English

SQL 查询未达到我的预期

[英]SQL QUERY Not resulting what i expect

I am confused with this code, i have created stored proc on mysql and this is my stored procedure code我对这段代码感到困惑,我在 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

This is the resul from CALL getChats('USER15703082085d99007096571')这是CALL getChats('USER15703082085d99007096571')

https://puu.sh/EpRhZ.png Result from Heidi SQL https://puu.sh/EpRhZ.png海蒂的结果 SQL

https://puu.sh/EpRmz.png Result from phpmyadmin https://puu.sh/EpRmz.png结果来自 phpmyadmin

https://puu.sh/EpRub.png Result from php pdo https://puu.sh/EpRub.png结果来自 php pdo

My php code我的 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());

What i need is i can fetch data on my php我需要的是我可以在我的 php 上获取数据

No need to use dynamic SQL in the stored procedure.无需在存储过程中使用动态 SQL。 Also, procedure parameters can be used as is (not as @param).此外,过程参数可以按原样使用(而不是@param)。

The code with correct parameter use would looks like:正确使用参数的代码如下所示:

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

The use of the GROUP BY in the query looks weird.在查询中使用GROUP BY看起来很奇怪。 Not sure what you are trying to do with that.不知道你想做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM