简体   繁体   中英

Sql query involving two tables

I have two tables, tbl_msg ...

tbl_msg

tbl_user

tbl_user

I want to select all the msgs from tbl_msg where toid=42 along with respective names of the person(instead of fromid) from whom msg has been sent. Result should look something like this..

|fromid(name, not the id)| Msg| toid(name!,which belongs to id 42)|some other column from msgid|

Query:

select tbl_msg.[MsgId]       
  ,tbl_User.FirstName  as sentby    
  ,tbl_msg.[ToId]
  ,tbl_msg.[Msg] 
from 
   tbl_msg 
inner join 
   tbl_User on tbl_msg.FromId = tbl_User.ID  
where 
   tbl_msg.ToId = 42

but this will only give me name of corresponding fromid and not names for both toid and fromid

How can this be done?

You have to join user two times:

select m.[MsgId]
  ,u1.FirstName  as sentby
  ,u2.FirstName as sentTo
  ,m.[Msg]
from tbl_msg m
inner join tbl_User u1 on m.FromId = u1.ID
inner join tbl_User u2 on m.ToId = u2.ID
where m.ToId = 42

Try to change ON tbl_msg.FromId=tbl_User.ID to on tbl_msg.ToId=tbl_User.ID instead:

select tbl_msg.[MsgId]       
,tbl_User.FirstName  as sentby    
,tbl_msg.[ToId]
,tbl_msg.[Msg] from tbl_msg inner join tbl_User 
 on tbl_msg.ToId=tbl_User.ID 
 where   tbl_msg.ToId=42

Hope this query will helps you.

select tbl_msg.[MsgId]       
  ,u1.FirstName  as sentby    
  ,u2.FirstName as FromSent
  ,tbl_msg.[ToId]
  ,tbl_msg.[Msg] from tbl_msg 
  inner join tbl_User u1 on tbl_msg.FromId=u1.ID  
  inner join tbl_User u2 on u1.ToID =  u2.ID
  where tbl_msg.ToId=42

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