需要一些编写 MySQL 查询的支持
我正在用 PHP/MySQL 编写一个基本的消息脚本,但现在我陷入了数据库查询。我将不胜感激任何提示或帮助(:
我正在使用两个表,因为一条消息可以发送给多个用户:
messages:
id | sender_id | subject | ...
message_receivers:
message_id | receiver_id | ...
我现在想做的是向他选择的用户显示一条消息。但我想显示用户在该对话中的整个消息历史记录(在浏览器中跳转到他选择的消息历史记录)通过连接执行此操作非常简单:
SELECT * FROM messages
JOIN message_receivers
ON messages.id = message_receivers.message_id
WHERE sender_id = x
AND receiver_id = y
但现在我丢失了消息的其他接收者的信息,而且我不知道如何做到这一点!有什么想法吗? (:
I'm writing a basic message-script in PHP/MySQL but I'm stuck at a database query right now. I'll appreciate any hints or assistance (:
I'm using two tables, since a message can be sent to several users:
messages:
id | sender_id | subject | ...
message_receivers:
message_id | receiver_id | ...
What I want to do now is display a message to the user that he selects. But I want to show the whole message history the user had in that conversation (jumping in browser to the one he selected). Doing this with a join is quite simple:
SELECT * FROM messages
JOIN message_receivers
ON messages.id = message_receivers.message_id
WHERE sender_id = x
AND receiver_id = y
But now I'm missing the information of other receivers of a message! And I have no clue how to get this information. Any ideas for that? (:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
再次加入
message_receivers
表以检索消息的其他收件人:您感兴趣的收件人将位于
recipient
列中(在每个结果记录中)。其他收件人将位于carboncopy
列中(每个结果记录一个)。如果 Carboncopy 为 NULL,则该消息只有一个接收者。Join the
message_receivers
table one more time to retrieve the other recipients of the message:The recipient that your are interested in will be in column
recipient
(in every result record). Other recipients will be in columncarboncopy
(one per result record). Ifcarboncopy
isNULL
, then the message had only a single receiver.如果您想查看消息的所有接收者,请删除 were 子句的第二部分:
同时您需要指定 message_id,因为这会让前端用户感到困惑
If you want to see all the receivers of a message then remove the second part of the were clause:
at the same time you will want to specify the message_id because this will be to confusing to the user on the front end
由于以下子句,您缺少有关消息的其他接收者的信息:
这将结果集限制为仅接收者
y
。删除该条款,您将获得所有这些。不过,您可能也会收到sender_id = x
处发送的每条消息,因此您需要通过指定message_id
来限制查询。所以你的最终查询应该是这样的:
You're missing information about other receivers of the message because of the clasue:
This restricts the result set to just receiver
y
. Remove the clause, and you'll get them all. However you'll probably get every message sent wheresender_id = x
as well, so you'll need to limit the query by specifying amessage_id
.So your final query should look something like this:
您不需要将结果限制为receiver_id = y,是吗?
您也可以用不同的方式编写语句并轻松返回接收者 ID:
you don't need to restrict your result to receiver_id = y, do you?
Also you might write the statement in a different way and easily return receivers ids: