简体   繁体   English

如何在 MySQL 上获取唯一(反之亦然)字段

[英]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:假设我的 MySQL 表上有这些行:

table1:表格1:

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.我编写了一个查询来检索列 column1 和 column2 上具有相似反之值的数据(id:1 和 id:3),但我无法查询没有相似反之行的数据( id: 2 & id: 4) 或者是独一无二的。

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

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

A simple solution would be to use your query in the WHERE clause to filter out similar rows:一个简单的解决方案是在WHERE子句中使用您的查询来过滤掉相似的行:

SELECT * 
FROM table1 t1
WHERE (column1, column2) NOT IN
   (SELECT t1.column1, t1.column2 
    FROM table1 t1
    INNER JOIN table1 t2
       ON t1.column1 = t2.column2 AND t1.column2 = t2.column1)

Demo here演示在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM