Home All Groups Group Topic Archive Search About

query same table twice for different users in one query?

Author
8 Sep 2006 7:30 AM
Paul
How do I do the following in ONE query:

I have a table, it has the structure of
msgID, fromUserID, toUserID, msgContent

fromUserID and toUserID are numerical IDs, linked to another table
(users), which has a first and last names for each userID.

What I'd like is to be able to send a query that will result in getting
back the expanded (first/last names) versions of both toUser and
fromUser. In other words, I'd like to get back something that looks
like:

msgID       From                     To                   Content
1              John Doe               Mary Goe          Hello
2              Mary Goe               John Doe          Hey.

instead of

msgID       From                     To                   Content
1              1                    2                      Hello
2              2                    1                      Hey.


How can I do it? I understand how to get it to display the To or the
Show quote
>From in its expanded form but not both.
Any ideas?
Thanks!

Author
8 Sep 2006 7:36 AM
Chris Lim
Paul wrote:
> How can I do it? I understand how to get it to display the To or the
> >From in its expanded form but not both.

Just join onto your Users table twice.

SELECT m.MsgID,
             u1.Name AS FromUser,
             u2.Name AS ToUser,
             m.msgContent
FROM Msgs m
INNER JOIN Users u1
  ON u1.UserID = m.FromUserID
INNER JOIN Users u2
  ON u2.UserID = m.ToUserID
Author
8 Sep 2006 4:41 PM
Paul
This is great, thanks Chris (I did need to add some parentheses in what
you sent, otherwise it worked).

However, how should I modify that query so that it also returns data if
one of the two IDs (the toUser or the fromUser) is null?

In other words, I might have a string in the db that is
msgID               fromID          toID         msgContent
3                 2                  NULL            "hello"

and i'd like to return that as well from this query, expanding the
fromID to the full name (as before) and leaving the toID empty...

Thanks!
Author
8 Sep 2006 4:46 PM
Paul
Well, I answered it myself: use LEFT OUTER JOIN instead of INNER JOIN.
Thanks again.

AddThis Social Bookmark Button