简体   繁体   中英

How can I select a field table that has a value in table1 but is NULL in table2?

I am developing a chat app using PHP and MySQL. I have 4 tables: users, friend_request, friends and chats. When a user clicks on 'Add Friend' button, I want to display all the members from 'users' table who are not friends with the user (from the 'friends' table). Friends table = friend_id user_id dat

Below is my code

SELECT * 
FROM users as t1 
LEFT JOIN friends as t2 
  ON (t1.user_id = t2.friend_id) OR (t1.user_id = t2.user_id)
WHERE t2.user_id IS NULL;

It returns

user_id* ++++ username ++++ email ++++ password ++++ gender ++++  country  ++++ status ++++ last_seen ++++ friend_id ++++  *user_id* ++++ dat**

2 wayne pro@ab.com ********* male  Nigeria 0 2021-08-13 6:31 NULL NULL 2021-08-12 1:58

1 rooney shot@ab.com ********* male  Nigeria 0 2021-08-13 6:32 NULL NULL 2021-08-12 2:00

Every record showed as expected, but the friend_id and user_id(from the friends table, I guess) are NULL.

Problem now is, I tried using PHP to output the value of user_id (from the first user_id which has a value 2 and 1 respectively), but it appears to be empty. Where did I get it wrong? I'm new to this.

You will need to alias the column( user_id ) like the way you alias the table name as t1 and t2. Since, both of the tables have columns with same column name. You can try something like this in your query:

SELECT t1.user_id as main_user_id

And in php, instead of using user_id , you will need to use main_user_id

Remove this condition WHERE t2.user_id IS NULL; your query

SELECT * 
FROM users as t1 LEFT JOIN friends as t2 ON (t1.user_id = t2.friend_id) OR (t1.user_id = t2.user_id)

The immediate solution to your problem is to only select columns from the first table:

select t1.*

In other words, don't include the columns from the friends table in the result set. Then there will be no confusion.

In general, select * should be avoided -- and even with a table alias. You should only select the columns that you need. This is insurance to protect your code from table changes in the future.

That said, your code seems to be missing a condition on the current user. I would

SELECT u.*
FROM users u
WHERE NOT EXISTS (SELECT 1
                  FROM friends f
                  WHERE (u.user_id, ?) IN ( (f.user_id, f.friend_id), (f.friend_id, f.user_id) )
                );

The ? is a parameter placeholder for the current user.

Also note the use of meaningful table aliases, which are abbreviations for the table names, making the query easier to read.

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