chat Table
-------------------------------------------------------
msg_id msg(description of msg) sender(id) receiver(id)
-------------------------------------------------------
1 hello 2 1
1 how are you 1 2
----------------------------------------------------------
user table
-----------------------
u_id username
-----------------------
1 usman
2 Ali
---------------------
这里你看到两个表用于聊天,一个表用于用户 我在这两个表之间建立了关系,但我觉得如何从这些表中提取数据很困难。
我想要的......
我想用其用户名和每个收发器名称及其用户名如Facebook聊天提取每个发件人msg,以便我进行此查询
我把这个查询放在数据库中
select u.user_name UserName,msg.msg
from user u,messages msg
where (msg.sender or msg.receiver)=(select u_id from user where u_id= 1 )
and msg.sender=1
order by msg.msg_id desc
但此查询重复发件人邮件,其中包含收件人姓名和发件人姓名
的收件人邮件我想显示发件人和reciver msg show与他们的名字分开告诉我任何方法我如何解决它。
答案 0 :(得分:2)
你拥有的东西永远不会奏效。 or
比较将返回一个布尔值true / false值,然后将其与u_id
的值进行比较。由于u_id
查询被硬编码为仅返回1
,因此您有效地执行了where true/false = 1
。
您需要加入user
表两次(一次为接收者,一次为发件人):
SELECT sender.user_name, receiver.user_name, msg.msg
FROM msg
LEFT JOIN user AS sender ON msg.sender_id = sender.u_id
LEFT JOIN user AS receiver ON msg.receiver_id = receiver.u_id
ORDER BY msg.msg_id
答案 1 :(得分:0)
select users.name, messages.msg .... Etc from messages inner join users on msgs.userid = user.id where (sender = :sndr and receiver = :rcvr) or (sender = :rcvr and receiver= :sndr) order by date desc;
take note of the named parameters there. That would return the conversation between the two users