简体   繁体   English

涉及两个表的SQL查询

[英]Sql query involving two tables

I have two tables, tbl_msg ... 我有两个表, tbl_msg ...

tbl_msg

tbl_user 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. 我想从tbl_msg中选择toid = 42的所有msg,以及从其发送msg的人的姓名(而不是fromid)。 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 但这只会给我对应的fromid的名称,而不会给我toid和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: 尝试将ON tbl_msg.FromId=tbl_User.ID更改为on tbl_msg.ToId=tbl_User.ID

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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