Question

I really worked on this weird code a lot, but I couldn't find what I'm looking for I searched on your wonderful website for an answer as usually I find it here, but none found

however, I have two tables that contains let say one column in the first table and two columns in the other.

I want to select all the records in the first table (the one column table) that doesn't match in the second table columns.

If you look here:

table 1

username

user1 user2 user3 user4 user5

And

table 2

you | friend

('user1', 'user2') ('user2', 'user3') ('user3', 'user1') ('user4', 'user3')

so basically What I want the records that never match 'user1' in table 1 and table 2 also I don't want anything that match 'user1' on the other side of the column and vise-verse

In conclusion, I want the returns of the field username to be as in order 'user4' 'user5'

So now you have the picture I have this link Live demo

so you don't need to worry about write any DB

Thanks.

Was it helpful?

Solution

Here is an updated answer following the conversation with OP:-

SELECT username
FROM (
  SELECT username FROM users
  UNION
  SELECT you FROM friends
  UNION
  SELECT friend FROM friends
) everybody
WHERE everybody.`username` != 'user1'

Substitute the username being test in the final string.

The UNION does a DISTINCT by default, removing any extra results.

====================== original answer from here ======================

I don't understand your question - but this may give you an idea of where to start...

SELECT username
FROM users
WHERE username NOT IN (
  SELECT you
  FROM friends
  UNION
  SELECT friend
  FROM friends
  )

This is probably more efficient, especially if indexes exist to cover the EXISTS:-

SELECT u.username
FROM users u
WHERE NOT EXISTS (
  SELECT *
  FROM friends f
  WHERE (f.you=u.username OR f.friend=u.username)
  )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top