Answer the question
In order to leave comments, you need to log in
How to select only those records that do not intersect and only those that intersect?
There is a table with fields: user_id, friend_user_id.
Subscription entries are added to the table from each user. They say user_id is subscribed to user_friend_id, and if there are 2 entries in the table, then such users are already considered friends.
The questions are as follows:
1. How to select only cross-records from the table, i.e. User1 is subscribed to User2 and User2 is subscribed to User1.
2. How to select only non-overlapping records from a table. those. those records where the first user is following another, but the other is NOT following the first.
I’ll say right away about the second part of the question, I found the answer, but is it really the right solution?
SELECT DISTINCT a.user_id
FROM user_friend a INNER JOIN user_friend b
ON a.friend_user_id = b.user_id
AND b.friend_user_id <> a.user_id
WHERE a.user_id = ?
Answer the question
In order to leave comments, you need to log in
one.
SELECT `t1`.*
FROM `table` AS `t1`
JOIN `table` AS `t2` ON `t2`.`user_id` = `t1`.`friend_user_id`
AND `t2`.`friend_user_id` = `t1`.`user_id`
SELECT `t1`.*
FROM `table` AS `t1`
JEFT JOIN `table` AS `t2` ON `t2`.`user_id` = `t1`.`friend_user_id`
AND `t2`.`friend_user_id` = `t1`.`user_id`
WHERE `t2`.`user_id` IS NULL
Using [NOT] EXISTS
SELECT *
FROM user_friend uf1
WHERE [NOT] EXISTS ( SELECT NULL
FROM user_friend uf2
WHERE uf2.friend_user_id = uf1.user_id )
AND friend_user_id > user_id
.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question