如何将另一个表加入此查询

时间:2015-01-02 12:15:19

标签: mysql join

这是第一次看到如此复杂的查询。以下是查询,我需要加入另一个名为" 个人资料"的表格。在 profile_id

表格结构

enter image description here

原始查询

SELECT a.*
    FROM messages a
    INNER JOIN
    (
        SELECT message_replay_id, MAX(message_id) AS latest_message
        FROM messages
        WHERE message_from = '1' || message_to = '1'
        GROUP BY message_replay_id 
    ) b
    ON a.message_replay_id = b.message_replay_id
    AND a.message_id = b.latest_message
    ORDER BY a.message_id DESC

所以,它将加入 message_to = profile_id

这就是我'我正在尝试

SELECT a.* FROM messages a
    INNER JOIN(SELECT message_replay_id, MAX(message_id) AS latest_message FROM messages WHERE message_from = '1' || message_to = '1' GROUP BY message_replay_id ) b
    ON a.message_replay_id = b.message_replay_id AND a.message_id = b.latest_message
    INNER JOIN(SELECT * AS latest_profile FROM PROFILES WHERE profile_id = b.latest_message ) c
    ON a.message_replay_id = b.message_replay_id AND a.message_id = b.latest_message
ORDER BY a.message_id DESC

错误消息

Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS latest_profile FROM profiles WHERE profile_id = b.latest_message ) c
    ON a.m' at line 4

帮助我们,我将如何加入另一张桌子。

1 个答案:

答案 0 :(得分:1)

您无法在from子句中的子查询中引用表别名。代替:

SELECT m.*
FROM messages m INNER JOIN
     (SELECT message_replay_id, MAX(message_id) AS latest_message
      FROM messages
      WHERE message_from = '1' || message_to = '1'
      GROUP BY message_replay_id
     ) mm
     ON m.message_replay_id = mm.message_replay_id AND
        m.message_id = mm.latest_message INNER JOIN
     profiles p 
     ON p.profile_id = mm.latest_message
ORDER BY mm.message_id DESC;

另外:

  • as与[{1}}(一般情况下)不合适。它只能重命名一列。
  • 您无需在前两个表格之间重复*条件。
  • join的子查询是不必要的,会损害MySQL的性能。
  • 如果表别名是表缩写,则查询更容易理解。