gpt4 book ai didi

mysql - sql表的唯一对

转载 作者:行者123 更新时间:2023-11-30 22:17:33 25 4
gpt4 key购买 nike

如何从包含特定元素的两列中选择具有唯一对的 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) 中唯一的一对是 (cat, dog)、(cat, rat) 和 (deer, cat)。所以我想要行(1 或 5)、(2 或 4)和 3。

我试过了

select * from table GROUP BY A, B HAVING (A='cat' OR B='cat')

但这给了我同时包含 (cat, dog) 和 (dog, cat) 的行。我只需要其中之一。

如何应用 mySql 查询以仅获取具有不同对的行?

最佳答案

使用 where 和 not having 因为你没有聚合函数

select a, b
from table
where a = 'x' or b = 'x'
and (a,b) not in (select b,a from table);

对不同的行使用不同的

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

这似乎正是你要找的结果

关于mysql - sql表的唯一对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37766762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com