-2

我有 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

4 回答 4

1

如果我理解您的问题,您想查看使用 vid =1 发表评论的人的姓名,无论他们是学生还是教授。这将做到这一点。ALEFT 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
于 2012-06-15T20:45:34.743 回答
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
于 2012-06-15T20:45:41.170 回答
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

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

于 2012-06-15T20:46:03.260 回答
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)
于 2012-06-15T20:49:10.190 回答