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

时间:2013-02-05 11:06:34

标签: 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           1        1 
39  1            42       1 

这就是我的表格。我想在此表上使用select查询来选择如下记录:

AllId
38
39
31
30
40
41
31
42

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

5 个答案:

答案 0 :(得分:3)

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

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

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

SELECT CASE LearnerId
            WHEN 1 THEN ConnectionId
            ELSE LearnerId
       END AS AllId
FROM tablename

答案 2 :(得分:1)

select  Id
from    YourTable
union all
select  LearnerId
from    YourTable
union all
select  ConnectionId
from    YourTable

答案 3 :(得分:0)

SELECT  Id AS AllId
FROM    YourTable
union all
SELECT  LearnerId AS AllId
FROM        YourTable
union all
SELECT  ConnectionId AS AllId
FROM        YourTable

答案 4 :(得分:0)

SELECT LearnerId AS AllId FROM tableName
WHERE ConnectionId = 1
UNION
SELECT ConnectionId AS AllId FROM tableName
WHERE LearnerId = 1