无法在查询中使用MySQL会话变量

时间:2017-10-31 08:51:43

标签: mysql

我有一个查询,我想使用会话变量,而不必在MySQL Workbench中反复输入数字进行调试。

这是查询:

SET @userId = 2;

SELECT
    id, 
    reply_to,
    from_id,
    to_id,
    message,
    created_time,
    is_viewed,
    IF(from_id = @userId, to_id, from_id) AS partnerId,
    IF(from_id = @userId, data->>'$.toUsername', data->>'$.fromUsername') AS partnerUsername,
    IF(from_id = @userId, data->>'$.toImage', data->>'$.fromImage') AS partnerImage
FROM message
WHERE
    (from_id = @userId OR to_id = @userId) AND
    is_active = 1
ORDER BY id DESC
LIMIT 50;

该查询返回0结果。但如果我把它改为:

SELECT
    id, 
    reply_to,
    from_id,
    to_id,
    message,
    created_time,
    is_viewed,
    IF(from_id = 2, to_id, from_id) AS partnerId,
    IF(from_id = 2, data->>'$.toUsername', data->>'$.fromUsername') AS partnerUsername,
    IF(from_id = 2, data->>'$.toImage', data->>'$.fromImage') AS partnerImage
FROM message
WHERE
    (from_id = 2 OR to_id = 2) AND
    is_active = 1
ORDER BY id DESC
LIMIT 50;

然后一切都按预期工作。为什么它不能像我期望的那样工作?

1 个答案:

答案 0 :(得分:1)

来自MySQL docs

  

用户变量旨在提供数据值。它们不能直接在SQL语句中用作标识符或标识符的一部分,例如在需要表或数据库名称的上下文中,或作为SELECT等保留字。

因此,您只能在应用程序代码中使用变量。 例如PHP:

$query = "SELECT
    id, 
    reply_to,
    from_id,
    to_id,
    message,
    created_time,
    is_viewed,
    IF(from_id = :userId, to_id, from_id) AS partnerId,
    IF(from_id = :userId, data->>'$.toUsername', data->>'$.fromUsername') AS partnerUsername,
    IF(from_id = :userId, data->>'$.toImage', data->>'$.fromImage') AS partnerImage
FROM message
WHERE
    (from_id = :userId OR to_id = :userId) AND
    is_active = 1
ORDER BY id DESC
LIMIT 50";
$stmt = $pdo->prepare($query);
$stmt->execute([':userId' => 2]);
$data = $stmt->fetchAll();