如何在MySql表中选择具有来自包含特定元素的两列的唯一对的所有行。在包含A列和B列的表中,我需要在A或B中包含x的所有行,但是使用唯一(A,B)配对,顺序无关紧要。
例如,
-----------------
+ id | A | B
+ 1 | cat | dog
+ 2 | cat | rat
+ 3 | deer | cat
+ 4 | rat | cat
+ 5 | dog | cat
(A,B)中的独特对是(猫,狗),(猫,大鼠)和(鹿,猫)。所以我想要行(1或5),(2或4)和3。
我试过了
select * from table GROUP BY A, B HAVING (A='cat' OR B='cat')
但这给了我两行(猫,狗)和(狗,猫)的行。我只需要其中一个。
如何应用mySql查询以便只获取具有不同对的行?
答案 0 :(得分:0)
因为你没有聚合功能而使用的地方和没有地方
select a, b
from table
where a = 'x' or b = 'x'
and (a,b) not in (select b,a from table);
对不同的行使用distinct
select distinct a, b
from table
where a = 'x' or b = 'x'
and (a,b) not in (select b,a from table);
根据您提供以下查询的示例
select id, b, a
from prova
where a = 'cat' or b = 'cat'
and (a,b) not in (select b,a from prova);
order by id desc
返回
3 deer cat
2 cat rat
1 cat dog
这似乎是您正在寻找的结果