2015-01-02 56 views
0

這是我第一次看到這樣一個複雜的查詢。以下是查詢,我需要加入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 

所以,這將加入ON 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 

幫助我的傢伙,我怎麼會加入另一個表。

+2

提供適當的DDL您的表定義 –

+1

擴展@ MKhalidJunaid的點...考慮下列行爲這種簡單的兩步過程:1.如果您還沒有這樣做,提供適當的DDL(和/或sqlfiddle ),這樣我們就可以更容易地複製問題。 2.如果您尚未這樣做,請提供與步驟1中提供的信息相對應的所需結果集。 – Strawberry

+0

'SELECT * AS latest_profile'沒有意義。 'AS'用於給'SELECT'列表中的表或單列賦予一個別名。你不能給'*'別名。另外,你的第二個'ON'子句應該在'c'子查詢中引用一些東西。 – Barmar

回答

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*(一般)。它只能重命名一列。
  • 您不需要重複前兩個表格之間的join條件。
  • profiles的子查詢是不必要的,會影響MySQL的性能。
  • 如果表別名是表縮寫,查詢更容易遵循。
相關問題