0

我在 Mysql 中有两个表。

message -> msg_id(pk) and message(varchar)
track_record -> tr_id(pk), msg_id (foreign key), object_id (to whom the message is sent), profile_id(who sent the message)

现在我想创建一个查询,它给我消息和给定 object_id 的发件人资料 ID。

例如说我有object_id 1。

现在我想查看发送给 id 为 1 的用户的所有消息。

编辑答案以添加我尝试过的查询

SELECT m.message, u.profile_profile_id FROm `message` as m, `user_track_record` as u 
WHERE msg_id IN 
      (SELECT message_msg_id FROM user_track_record WHERE object_profile_id = 1) 
      and u.profile_profile_id IN 
      (SELECT profile_profile_id from `user_track_record` WHERE object_profile_id = 1)

想要在 SQL 和 HQL 中执行此操作。任何帮助表示赞赏。谢谢

4

1 回答 1

0

您的 SQL 查询过于复杂。

从简单的事情开始:

选择发送给用户 1 的所有 track_records:

select tr.* from track_record tr where tr.object_id = 1

现在您希望将消息链接到跟踪记录。这是使用连接完成的:

select tr.*, m.* from track_record tr 
inner join message m on m.msg_id = tr.msg_id
where tr.object_id = 1

现在您只需要发件人的 ID 和邮件正文:

select tr.profile_id, m.message 
from track_record tr 
inner join message m on m.msg_id = tr.msg_id
where tr.object_id = 1

在 HQL 中,查询几乎相同。您有一个 Message 实体和一个 TrackRecord 实体。TrackRecord 与 Message 具有多对一关联。它还与发送者和接收者具有多对一关联

select tr.sender.id, m.message
from TrackRecord tr
inner join tr.message m
where tr.receiver.id = 1
于 2012-05-18T10:40:34.477 回答