简体   繁体   中英

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

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')

https://puu.sh/EpRhZ.png Result from Heidi SQL

https://puu.sh/EpRmz.png Result from phpmyadmin

https://puu.sh/EpRub.png Result from php pdo

My php code

$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

No need to use dynamic SQL in the stored procedure. Also, procedure parameters can be used as is (not as @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. Not sure what you are trying to do with that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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