简体   繁体   English

PHP-MYSQL-消息/用户表联接问题

[英]PHP - MYSQL - Messages/Users table join issue

I'm using MYSQL to display some data from specific tables... However I have small problem.. 我正在使用MYSQL来显示特定表中的一些数据。但是我有一个小问题。

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. 我查询“数据库名称消息”,其中有2列user_one和user_two。 The currently logged in user id can be eather user_one or user two (This fields are id's of users)... 当前登录的用户ID可以是eather user_one或用户2(此字段是用户的ID)...

So I use SELECT ... FROM table_name WHERE user_one = $id OR user_two = $id); 所以我使用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. 并且可以正确显示我当前登录的user_one或user_two用户的消息。 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: 因此,如果username1已登录,则当我输出消息时,我希望它输出:

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

If username2 is logged in then it would say From: username1 如果username2已登录,则提示: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 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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