使用IF ..Then ..Else with select queries?

时间:2012-06-15 20:37:09

标签: sql sql-server sql-server-2008 sql-server-2005

我有3张这样的表:

comment表:

commentId pid    sid       text      vid
1          1     null    comment 1    1
2         null    1     comment 2    1
3          2     null    comment 3    1

student表:

sid     firstname   lastname
1         john       adam
2         joan       adam

professor表:

pid    firstname   lastname
1       mark        abram
2       sean        hoak

我想编写一个查询,以便返回结果:

firstname    lastname
mark          abram
john          adam
sean          hoak

if (select query ==null) 
   then (select query 1) 
   else select (query 2)

我尝试了以下内容:

if((select pid from comment==null)
then select student.firstname , student.lastname from student where sid in (select sid from comment where vid=1)

else
(select professor.firstname ,professor.lastname from professor where pid in (select pid from comment where vid=1)

但没有运气。

如何实现想要的结果?

4 个答案:

答案 0 :(得分:1)

如果我理解你的问题,你想看到谁发布了vid = 1的评论的名字,无论他们是学生还是教授。这样做会。 LEFT JOIN带来左表中的所有内容,包括空值。只需LEFT JOIN两个相应的ID,您就可以获得所需的内容。

SELECT ISNULL(p.firstname,s.firstname), ISNULL(p.lastname,s.lastname) --,comment or whatever other things you want to show
FROM Comment C
LEFT JOIN professor P ON P.pid = c.pid
LEFT JOIN student s ON s.sid = c.sid
WHERE vid = 1

答案 1 :(得分:1)

如果我理解正确,这个查询应该:

SELECT A.commentId, ISNULL(B.firstname,C.firstname) firstname, ISNULL(B.lastname,C.lastname) lastname
FROM comment A
LEFT JOIN student B
ON A.sid = B.sid
LEFT JOIN professor C
ON A.pid = C.pid

答案 2 :(得分:1)

试试这个:

SELECT COALESCE(p.firstname, s.firstname), COALESCE(p.lastname, s.lastname)
FROM comments c
LEFT JOIN Professors p
ON c.pid = p.pid
LEFT JOIN Students s
ON c.sid = s.sid

有点讨厌,如果你创建了一个合并学生和教授的视图,可能会有所改进。

答案 3 :(得分:0)

select student.firstname , student.lastname 
from student 
where sid in (select sid from comment where vid=1 and pid is null)
UNION ALL
select professor.firstname ,professor.lastname 
from professor 
where pid in (select pid from comment where vid=1 and PID is not null)