数据库,查询实现

时间:2011-03-10 21:59:56

标签: sql

I have a table named USERS:  
userID  userName
1       Foo
2       Bar
3       Foobar

I also have a table named MAIL:
mailID    senderID   recipientID   subject     messageBody
1          1           2            Hello      testtesttest
2          1           3            Hello2     test1test1test1

我有一个包含字段From,To,Subject和Message Body的表单。 我的问题是,我该如何实施 查询,以便从MAIL表返回一个条目,说条目mailID = 1,用userName,主题和邮件正文中包含的实际名称填充字段?

3 个答案:

答案 0 :(得分:2)

SELECT m.mailid,
       m.subject,
       sender.userName,
       recepient.userName
FROM mail m
  JOIN users sender ON m.senderID = sender.userID
  JOIN users recepient ON m.recepientID = recepient.userID

答案 1 :(得分:2)

那将是(没有特定DBMS的语法特性)

select s.userName, r.userName, m.subject, m.messageBody 
    from mail m 
    inner join users s on m.senderID = s.ID
    inner join users r on m.senderID = r.ID

答案 2 :(得分:1)

select username, subject, messageBody from Mail m inner join users u on m.recipientid (or senderid) = u.userid where entryid = 1

应该这样做。