我有三张桌子:
User: UserId (pk)
FirstName
Lastname
Messages: MessageId (pk)
Heading
Body
User_Messages: UserId
MessageId
现在,实体设计者只创建两个表,并在表之间存在关联。 我试图选择UserId = value1和MessageId = value2的项目, 但似乎不能正确。实体查询会是什么样的?
答案 0 :(得分:0)
Select a.firstname, a.lastname, b.heading, b.body
from user a, Messages b, User_Messages c
where a.UserId = c.UserId and b.MessageId = c.MessageId
and c.UserId = value1 and c.MessageId = value2
答案 1 :(得分:0)
要仅选择彼此关联的用户/消息,您可以使用
SELECT u.UserId, u.FirstName, u.LastName, m.MessageId, m.Heading, m.Body
FROM User_Messages h
INNER JOIN User u ON h.UserId = u.UserId
INNER JOIN Messages m ON h.MessageId = m.MessageId
要选择所有用户(并添加他们的消息,如果有的话),请使用:
SELECT u.UserId, u.FirstName, u.LastName, m.MessageId, m.Heading, m.Body
FROM User u
LEFT JOIN User_Messages u ON h.UserId = u.UserId
LEFT JOIN Messages m ON h.MessageId = m.MessageId
最后,要选择消息并为每个消息添加用户信息,请使用:
SELECT u.UserId, u.FirstName, u.LastName, m.MessageId, m.Heading, m.Body
FROM Messages m
LEFT JOIN User_Messages h ON h.MessageId = m.MessageId
LEFT JOIN User u ON h.UserId = u.UserId