2013-06-30 102 views
0

我有3個表:查詢別名與INNER JOIN和LIMIT 1

Message_group 
    --------------------------------------- 
    message_group_id | profile_id | group_id 
    ---------------------------------------- 

    1     sN07X2 4934Me 
    2     abcde2 4934Me 
    3     Red3zw 3492Ga 
    4     Hgr43s 3492Eh 
    ---------------------------------------- 

    Private_Message 
    ---------------------------------------- 
    msg_id | msg_txt | profile_id | occured_at 
    ----------------------------------------- 
    1   Hello  abcde2  2013-06-26 
    2   Bye Bye  abcde2  2013-06-26 
    3   Ciao  Red3zw  2012-06-26| 
    ----------------------------------------- 

    Users 
    ------------------------------------------- 
    profile_id | name | sirname | 
    sN07X2  Jin  OO 
    abcde2  Gerry UU 
    Red3zw  Lola  YY 
    Hgr43s  Scot  EE 

我想有結果一樣,

profile_id | profile_id2 | group_id | msg_text 
    abcde2   sN07X2  4934Me  abcde2 

我想有這樣的結果,但像msg_text只有最後messege 。 此查詢,我已經寫了給我這個結果,我不知道如何與限制1加場消息:

profile_id | profile_id2 | group_id | 
    abcde2   sN07X2  4934Me 

QUERY:

SELECT * FROM message_group a 
JOIN message_group b ON a.group_id=b.group_id 
INNER JOIN users ON users.profile_id = b.profile_id 
WHERE a.profile_id = 'sN07X2' 
AND b.profile_id != a.profile_id 
+0

你如何加入private_message與message_group? – fthiella

+0

我真的不明白你想要完成什麼。我瞭解每個用戶都屬於一個組。似乎privete消息沒有接收器,因此該模型假定每個用戶只能發送一條消息給它所屬的組,並且它只能屬於一個組?我只是沒有得到模型... –

回答

1

沒有測試,但它可能是

SELECT a.*,b.*,(SELECT msg_txt FROM Private_Message p WHERE p.profile_id=a.profile_id ORDER BY occured_at DESC LIMIT 1) 
FROM message_group a 
JOIN message_group b ON a.group_id=b.group_id 
INNER JOIN users ON users.profile_id = b.profile_id 
WHERE a.profile_id = 'sN07X2' 
AND b.profile_id != a.profile_id 

但是,我真的不明白你的病情:AND b.profile_id != a.profile_id ?? !!

+0

謝謝你太多了!完善邏輯。我使用了AND b.profile_id!= a.profile_id,因爲結果是2行,我只需要一個 –