Answer the question
In order to leave comments, you need to log in
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
-- Используя 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;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question