简体   繁体   中英

Query alias with INNER JOIN and LIMIT 1

I have 3 table:

    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

I want have the result like that

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

i would like have this result but like msg_text only the last messege. this query that i have wrote give me this result, i don't know how add the field msg with limit 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

Not tested, but it could be

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

But, I really don't understand your condition : AND b.profile_id != a.profile_id ??!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM