Mysql在where子句中选择别名

时间:2014-06-09 10:25:28

标签: mysql sql

我在where子句中使用别名时遇到问题。

我有这样的表格: enter image description here

我存储用户,他们可以互相发送消息。消息数据存储在social_messages表中,包含core_users_sender和core_users_receiver ids。

现在,当用户登录系统时,我想只显示与他/她进行对话的那些用户的列表。

(登录core_users.id为6) 我使用此查询并获取与用户进行对话的朋友的ID,没有问题:

SELECT
    messages.id,
    messages.status,
    messages.send_date,
    IF(
        core_users_sender = 6,
            core_users_receiver,
            core_users_sender
    ) as friend_id
FROM
    social_messages messages
WHERE
      messages.core_users_sender = 6
        OR
      messages.core_users_receiver = 6
GROUP BY
  friend_id

但问题是,当我尝试使用friend_id从core_users表中获取数据并使用查询时:

SELECT
    messages.id,
    messages.status,
    messages.send_date,
    IF(
        core_users_sender = 6,
            core_users_receiver,
            core_users_sender
    ) as friend_id,
    users.fullname
FROM
    social_messages messages,
    core_users users
WHERE
      users.id = friend_id
      AND
      (
          messages.core_users_sender = 6
            OR
          messages.core_users_receiver = 6
      )
GROUP BY
  friend_id

我收到错误,因为friend_id无法在where子句中使用,因为它是在select

中计算的

3 个答案:

答案 0 :(得分:5)

您不能在where子句中使用别名。使用原始子查询

where users.id = IF(
                core_users_sender = 6,
                core_users_receiver,
                core_users_sender
        )
  

不允许在WHERE子句中引用列别名,因为在执行WHERE子句时可能尚未确定列值。

答案 1 :(得分:0)

我建议您以这种方式重新排序查询:

SELECT
    messages.id,
    messages.status,
    messages.send_date,
    users.fullname,
    IF(
        messages.core_users_sender IS NOT NULL,
        messages.core_users_receiver,
        messages.core_users_sender
    ) as friend_id
FROM
    social_messages messages
    left join core_users users_sender
        on users_sender.id = messages.core_users_sender
        and messages.core_users_sender = 6
    left join core_users users_receiver
        on users_receiver.id = messages.core_users_receiver 
        and messages.core_users_receiver = 6

WHERE
    users_sender.id IS NOT NULL OR users_receiver.id IS NOT NULL

答案 2 :(得分:0)

您可以为您的表添加别名并使用它

        SELECT messages.*, users.fullname
        FROM
        (SELECT
            messages.id,
            messages.status,
            messages.send_date,
            IF(
                core_users_sender = 6,
                    core_users_receiver,
                    core_users_sender
            ) as friend_id
        FROM
            social_messages messages
        WHERE
              messages.core_users_sender = 6
                OR
              messages.core_users_receiver = 6
        GROUP BY
          friend_id) as `messages`
        JOIN
              core_users users
        ON
              users.id = messages.friend_id