N
N
nedland1232021-12-20 10:58:30
SQL
nedland123, 2021-12-20 10:58:30

SQL query to select mismatch?

There is a table QEEN
ID AB
1 22 32
2 22 55
3 32 22
4 32 77

How to select only ID=2 and ID=4 with a SELECT query, that is, select an ID where there are no matches in A and B and vice versa B and A for different rows.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Slava Rozhnev, 2021-12-20
@nedland123

-- Используя WHERE NOT EXISTS
SELECT * 
FROM QEEN
WHERE NOT EXISTS (
  SELECT ID FROM QEEN REVERSE_QEEN WHERE REVERSE_QEEN.A = QEEN.B AND REVERSE_QEEN.B = QEEN.A
);

-- Используя LEFT JOIN
SELECT QEEN.* 
FROM QEEN
LEFT JOIN QEEN REVERSE_QEEN ON REVERSE_QEEN.A = QEEN.B AND REVERSE_QEEN.B = QEEN.A
WHERE REVERSE_QEEN.ID IS NULL;

-- Просто извращение, но тоже должно работать :)
WITH ALL_QEEN AS (
  SELECT ID, A, B, 1 T FROM QEEN
  	UNION ALL
  	SELECT ID, B, A, 2 T FROM QEEN
) SELECT 
  MIN(ID) ID, A, B
FROM ALL_QEEN
GROUP BY A, B
HAVING COUNT(*) = 1 AND MIN(T) = 1;

Test SQL queries online

R
Rsa97, 2021-12-20
@Rsa97

LEFT JOIN and IS NULL

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question