来自两个表和多行的SQL查询

时间:2017-09-28 06:40:14

标签: sql ms-access

我有2张桌子。

fisrt:用户 enter image description here

第二个:消息 enter image description here

我的桌子关系:

enter image description here

我的问题是:我需要一个查询,它将所有的reciver信息(参数)以及MessageSenderID和MessageReciverID作为名称返回给我,而不是id。

我的疑问:

SELECT Message.MessageID, Message.MessageSubject, Message.MessageContent,
       u1.UserFisrtName + '' + u1.UserLastName AS Sender1,
       u2.UserFisrtName + '' + u2.UserLastName AS Reciver1
FROM Users AS u1,
     Users AS u2,
     Messages
WHERE u1.UserID = Message.MessageSenderID
  AND u2.UserID = Message.UserID
  AND u2.UserID = ***userid***

错误是:

  

没有给出一个或多个必需参数的值。

2 个答案:

答案 0 :(得分:0)

您应该使用JOIN语句

SELECT * FROM messages
JOIN user u1 ON (u1.id = message.MessageSenderID)
JOIN user u2 ON (u2.id = message.essageReciverID)

有关加入的更多信息:http://www.mysqltutorial.org/mysql-inner-join.aspx

有关参数问题,请参阅此问题:Pass parameters to sql script

参数可以如下使用:

WHERE u2.id = @userid

答案 1 :(得分:0)

SELECT Messages.MessageID, Messages.MessageSubject, Messages.MessageContent,
       s.UserFisrtName & ' ' & s.UserLastName AS Sender,
       r.UserFisrtName & ' ' & r.UserLastName AS Reciver
FROM (Messages
INNER JOIN Users AS s ON s.UserID = Messages.MessageSenderID)
INNER JOIN Users AS r ON r.UserID = Messages.MessageReciverID
WHERE r.UserID = **userid**;