MySQL内连接问题或其他平等解决方案

时间:2010-04-13 15:04:34

标签: database mysql

几个小时后,我正在弄清楚如何在这些表格中进行内部连接(这个问题简化了表格):

消息包含以下字段:

| id |内容|

message_relation 包含以下字段:

| id | message_id | sender_id | receiver_id |

用户包含以下字段:

| id |名字|

我要对此表做的是通过 receiver_id 为用户选择所有消息,但也想知道发件人姓名。我尝试过类似的东西:

SELECT *
FROM (
`message_relation`
)
JOIN `message` ON `message`.`id` = `message_relation`.`message_id`
JOIN `user` ON `message_relation`.`receiver_id` = `user`.`id`
WHERE `receiver_id` = '10'

使用此查询我只获取receiver_id名称,但无法弄清楚如何在此查询中找出sender_id。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:3)

您可以使用表别名多次加入user表:

SELECT m.content,
       us.name as 'sender',
       ur.name as 'receiver'
FROM   message_relation mr
JOIN   message m ON (m.id = mr.message_id)
JOIN   user us ON (us.id = mr.sender_id)
JOIN   user ur ON (ur.id = mr.receiver_id);

答案 1 :(得分:0)

替换'?????'与您的receiver_id:

SELECT message.id AS mid, message.content AS mcontent, user.name AS uname
FROM message,message_relation,user
WHERE
message_relation.message_id=message.id
AND message_relation.sender_id=user.id
AND message_relation.receiver_id='?????'

唷!没有经过测试,但你明白了。