Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

How to get unique (not vice-versa) fields on MySQL

The title may be misleading but i don't know how to formulate it better.

Suppose i have these rows on my MySQL table:

table1:

id    column1    column2
1     1          2
2     1          3  
3     2          1
4     3          4

I have written a query to retrieve data that have similar vice-versa values on columns column1 and column2 (id: 1 & id: 3), but I'm having trouble querying over data that don't have similar vice-versa rows (id: 2 & id: 4) or that are sort of unique.

EDIT: The query i've used to get vice-versa rows

SELECT * FROM table1 t1
INNER JOIN table1 t2
ON (t1.column1 = t2.column2 AND t1.column2 = t2.column1);
question from:https://stackoverflow.com/questions/65626194/how-to-get-unique-not-vice-versa-fields-on-mysql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use exists logic here:

SELECT id, column1, column2
FROM yourTable t1
WHERE NOT EXISTS (SELECT 1 FROM yourTable t2
                  WHERE LEAST(t2.column1, t2.column2) = LEAST(t1.column1, t1.column2) AND
                        GREATEST(t2.column1, t2.column2) = GREATEST(t1.column1, t1.column2));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...