Heim  >  Artikel  >  Backend-Entwicklung  >  关于站内用户私信的mysql语句

关于站内用户私信的mysql语句

WBOY
WBOYOriginal
2016-06-06 20:16:041129Durchsuche

私信数据表,6个字段:
id
parent 自联接,=0表示第一次发送的私信,非0表示对某id的回复
to_user 发给谁,用户的id
from_user 来自谁,用户id
message
date

比如在我的私信列表中(用户id=1),就可以查询to_user=1 or from_user=1 and parent=0的所有记录,

这样,对方的用户id是有了。问题是,怎么到users表里关联查询对方用户的信息呢

逻辑是:若to_user=1,那么用form_user字段和用户表里的相应字段关联;反之,若form_user=1,则用to_user字段和用户表字段去关联……

怎么写sql语句?

回复内容:

私信数据表,6个字段:
id
parent 自联接,=0表示第一次发送的私信,非0表示对某id的回复
to_user 发给谁,用户的id
from_user 来自谁,用户id
message
date

比如在我的私信列表中(用户id=1),就可以查询to_user=1 or from_user=1 and parent=0的所有记录,

这样,对方的用户id是有了。问题是,怎么到users表里关联查询对方用户的信息呢

逻辑是:若to_user=1,那么用form_user字段和用户表里的相应字段关联;反之,若form_user=1,则用to_user字段和用户表字段去关联……

怎么写sql语句?

可以用if 不过效率不知道有没有两次join好

<code>SELECT A.*,users.name FROM `A` INNER JOIN `users` ON if(A.to_user=1,A.form_user,A.to_user) = users.id  WHERE `A.to_user`=1 or `A.from_user`=1 and `A.parent`=0</code>

<code>select
    to_user.username as to_username,
    from_user.username as from_username
from message 
left join user as to_user on message.to_user = to_user.id
left join user as from_user on message.from_user = from_user.id
where...</code>

唉,按说不应该回答这种问题,自己查一下就知道了。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn