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

WBOY
Release: 2016-06-06 20:16:04
Original
1152 people have browsed it

私信数据表,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>
Copy after login

<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>
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template