SQL查询检索双方

时间:2019-02-02 15:26:52

标签: sql sql-server join

假设我有以下数据库表

Id = int
Source = nvarchar(1)
Destination = nvarchar(1)

基本上代表关系

Source -> Destination
Destination -> Source

这两种关系可以存在,或者只是其中之一,我想一排,可以代表我不能够找到什么样的SQL的加盟,我可以做到这一点。

我正在尝试编写一个SQL查询,该查询将返回双方的结果。 在所有示例中,我都希望检索“ A”的信息

如果表有无

Id = 0
Source = "A"
Destination = "B"

我想要下一行

FirstId = 0, SecondId = NULL

如果表有

Id = 1
Source = "B"
Destination = "A"

我想要下一行

FirstId = NULL, SecondId = 1

如果表有

Id = 0
Source = "A"
Destination = "B"
Id = 1
Source = "B"
Destination = "A"

我想要下一行

FirstId = 0, SecondId = 1

2 个答案:

答案 0 :(得分:1)

我想我会在表本身上尝试完全外部联接:

import telebot
import cnst

bot=telebot.TeleBot(cnst.token)

@bot.message_handler(content_types=["text"])
def handle_text (message):
    bot.forward_message(id, id, 86)

bot.polling(none_stop=True)

答案 1 :(得分:0)

如果我理解正确,则可以使用聚合:

select max(case when source = 'A' then id end) as a_id,
       max(case when source = 'B' then id end) as b_id       
from t
where source in ('A', 'B') and
      destination in ('A', 'B');