Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 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 Reply

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...