K
K
Kirito Asumo2021-11-01 04:05:31
SQL
Kirito Asumo, 2021-11-01 04:05:31

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

2 answer(s)
R
Rsa97, 2021-11-01
@Sparkis

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`

2.
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

A
Akina, 2021-11-01
@Akina

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 )

With WHERE EXISTS, pairs of friends are selected (records that have a reverse pair), with WHERE NOT EXISTS, records that do not have a reverse pair are selected.
If only one pair of two is needed for records that have an inverse, we add one more condition to the WHERE of the external query AND friend_user_id > user_id.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question