简体   繁体   中英

PHP - MYSQL - Messages/Users table join issue

I'm using MYSQL to display some data from specific tables... However I have small problem..

I'm trying to build some conversation system (for my learnin purpose)...

I query "database name messages" where I have 2 columns, user_one and user_two. The currently logged in user id can be eather user_one or user two (This fields are id's of users)...

So I use SELECT ... FROM table_name WHERE user_one = $id OR user_two = $id); and that display me messages properly where user_one or user_two is currently logged in user. It works fine...

However now I need to know how I join table users and pick only username of "other person", not logged one and display it on each message like "Message from..."!

So lets say I have following:

Users table:

id    username
--------------------------
1     username1 
2     username2 

Messages table:

id    title   user_one    user_two
--------------------------------------------
1     Title      1           2
2     Title2     2           1

So if username1 is logged in, when i output my messages i would like it to output:

Title    From
-----------------------------------------
Title    username2
Title2   username2

If username2 is logged in then it would say From: username1

So I want to display From username always of second person, not logged in one... I joined table regulary but it display me both users usernames...

Am I doing table structure wrong or how can I do that?

Thanks.

try this

   SELECT Messages.title As title ,Users.username as `FROM` FROM Users
   INNER JOIN  Messages 
   ON  Messages.user_two = Users.id 
   OR Messages.user_one = Users.id
   WHERE Users.username != 'username1'

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM