Sql 从同一个表中获取单列记录

Sql 从同一个表中获取单列记录,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我在从数据表中检索记录时遇到了一些问题。谁能给我一些建议吗 Id LearnerId ConnectionId IsApproved 3 1 38 1 5 39 1 1 7 1 31 1 13 1 30 1 31 1 40 1 34 41 1 1 35 31

我在从数据表中检索记录时遇到了一些问题。谁能给我一些建议吗

Id LearnerId ConnectionId  IsApproved   
3   1            38       1
5   39           1        1 
7   1            31       1 
13  1            30       1 
31  1            40       1 
34  41           1        1 
35  31           1        1 
39  1            42       1 
这就是我的桌子的样子。我想使用此表上的select查询选择以下记录:

AllId
38
39
31
30
40
41
31
42

如何编写查询以查找上述记录列表?我想收集除1之外的所有ID。

您可以在两个查询之间使用
联合all
。第一个将返回
connectionid
值,第二个将返回
learnerid
值:

select  Id
from    YourTable
union all
select  LearnerId
from    YourTable
union all
select  ConnectionId
from    YourTable
select ConnectionId as AllId
from LearnerConnections
where LearnerId = 1
union all
select LearnerId as AllId
from LearnerConnections
where ConnectionId = 1

请参见

您可以在两个查询之间使用
联合所有
。第一个将返回
connectionid
值,第二个将返回
learnerid
值:

select ConnectionId as AllId
from LearnerConnections
where LearnerId = 1
union all
select LearnerId as AllId
from LearnerConnections
where ConnectionId = 1

请参见

最终结果中包括哪些列?为什么
1
不会出现在最终结果中?我需要根据LearnerId=1或ConnectionId=1收集记录,结果将是没有1的单列,只有记录的其余部分会出现。最终结果中包括哪些列?为什么
1
不会出现在最终结果中?我需要根据LearnerId=1或ConnectionId=1收集记录,结果将是没有1的单列,只有记录的其余部分会出现。+1这将返回示例结果集,可能是OP想要的+1这将返回示例结果集,也许是OP想要的
SELECT  Id AS AllId
FROM    YourTable
union all
SELECT  LearnerId AS AllId
FROM        YourTable
union all
SELECT  ConnectionId AS AllId
FROM        YourTable
SELECT LearnerId AS AllId FROM tableName
WHERE ConnectionId = 1
UNION
SELECT ConnectionId AS AllId FROM tableName
WHERE LearnerId = 1