带子查询的MySql查询

时间:2014-10-27 19:22:24

标签: mysql join subquery

我在尝试进行简单查询时遇到了麻烦。 我的表是:

用户

+-------+----------+
| id    | username |
+-------+----------+

消息

+-------+-------------+------------+--------+
| id    | receiver_id | sender_id  | text   |
+-------+-------------+------------+--------+

我需要收到来自SEPECIFIC用户的所有消息(知道他的用户名)。 但我也需要获得接收者和发送者用户名。

我用过

SELECT *  from user U, messages M where (M.sender_id OR M.receiver_id)=(select id from user where username = 'Guy1') group by M.id

这有效,但现在我需要他们的用户名,所以我想到了类似的东西:

SELECT * from user U, messages M, (select username as Sender from user U1, messages M1 where M1.sender_id= U1.id)as Sub where (M.sender_id OR M.receiver_id)=(select id from user where username = 'Guy1') group by M.id

但是它没有给我我需要的东西,我怎样才能实现我想做的事情呢?

在结果中我需要类似的东西:

+-------+-------------------+------------------+
| text  | receiver_Username | sender_Username  | 
+-------+-------------------+------------------+

3 个答案:

答案 0 :(得分:2)

我认为以下查询将通过使用user table连接两次消息表来获得所需的结果。一个用于发送者,一个用于接收者

  SELECT  messages.text,sender.username,receiver.username   from messages
  inner join user as sender on sender.id = messages.sender_id
  inner join  user as receiver on receiver.id = messages.receiver_id

答案 1 :(得分:1)

也许我没有表达好,我需要获取sender_id的用户名和receiver_id的用户名以及文本。但只有在用户= User1的情况下你发布的所有这些查询都没有这样做 - Gabriele Prestifilippo 6秒前

sender_id的用户名和文字:

SELECT u.username, m.text FROM user AS u
LEFT JOIN messages AS m ON u.id = m.sender_id
WHERE u.username = 'Some_User';

receiver_id的用户名和文字:

SELECT u.username, m.text FROM user AS u
LEFT JOIN messages AS m ON u.id = m.receiver_id
WHERE u.username = 'Some_User';

组合:

SELECT u.username, m.text, x.text FROM user AS u
LEFT JOIN messages AS m ON u.id = m.receiver_id
LEFT JOIN messages AS x ON u.id = x.sender_id
WHERE u.username = 'User1'

答案 2 :(得分:0)

SELECT U.username, M.receiver_id, M.sender_id, M.text 
FROM user U 
LEFT JOIN messages AS M ON  U.id = M.sender_id