私信資料表,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好
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
select to_user.username as to_username, from_user.username as from_usernamefrom message left join user as to_user on message.to_user = to_user.idleft join user as from_user on message.from_user = from_user.idwhere...
唉,按說不應該回答這種問題,自己查一下就知道了。