2013-06-30 103 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行,我只需要一个 –