gpt4 book ai didi

sql - 选择 column2 不等于 column1 的行

转载 作者:搜寻专家 更新时间:2023-10-30 23:19:41 25 4
gpt4 key购买 nike

我需要有关 SQL 查询的帮助

我有这张 table

likes
friend friend2
1 2
2 1
3 1
4 5

我只需要选择一对彼此喜欢的 friend 。

通过我当前的选择,我得到了这个

 id     name         id     name
1709 Cassandra 1689 Gabriel
1689 Gabriel 1709 Cassandra
1501 Jessica 1934 Kyle
1934 Kyle 1501 Jessica

但预期的查询结果是:

 id     name        id     name
1709 Cassandra 1689 Gabriel
1501 Jessica 1934 Kyle

最佳答案

如果您确定每一对都在数据库中输入了两次(一次作为 A、B,然后再次作为 B、A),那么您可以使用此方法:

 SELECT friend, friend2
FROM yourtable
WHERE friend < friend2

如果可以有一些只输入一次的对,那么你可以使用这个:

 SELECT DISTINCT
LEAST(friend, friend2) AS friend,
GREATEST(friend, friend2) AS friend2
FROM yourtable

关于sql - 选择 column2 不等于 column1 的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8031725/

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