在SELECT语句中多次使用表

时间:2011-09-01 13:36:31

标签: sql-server select

我正在进行以下SQL调用:

SELECT dpt_id, 
dpt_title, 
dpt_active, 
dpt_parent
FROM tbl_department ORDER BY dpt_title

其中dpt_parent是父部门ID的整数值(另一部门的dpt_id)。

我希望上面调用的结果集包含该dpt_parent的dpt_title。我最初的尝试如下:

SELECT dpt_id, 
dpt_title, 
dpt_active, 
dpt_parent, 
    (SELECT dpt_title 
     FROM tbl_department 
     WHERE tbl_department.dpt_id = dpt_parent
     ) AS parent_title
FROM tbl_department ORDER BY dpt_title

使用此表单中的调用时,parent_title的所有值都为NULL 我可以看到使用相同的表这样令人困惑,这个问题的解决方案是什么?

6 个答案:

答案 0 :(得分:3)

SELECT d.dpt_id, 
d.dpt_title, 
d.dpt_active, 
d.dpt_parent,
p.dpt_title parent_title
FROM tbl_department d
LEFT JOIN tbl_department p ON d.dpt_parent = p.dpt_id
ORDER BY d.dpt_title

答案 1 :(得分:3)

使用表别名:

SELECT dpt_id, 
x.dpt_title, 
x.dpt_active, 
x.dpt_parent, 
    (SELECT dpt_title 
     FROM tbl_department 
     WHERE tbl_department.dpt_id = x.dpt_parent
     ) AS parent_title
FROM tbl_department x ORDER BY dpt_title

但你最好删除子选择并加入像:

SELECT 
     a.dpt_id
    ,a.dpt_title
    ,a.dpt_active
    ,a.dpt_parent
    ,b.dpt_title parent_title
FROM tbl_department      a
LEFT JOIN tbl_department b ON a.dpt_parent = b.dpt_id
ORDER BY a.dpt_title, b.dpt_title

答案 2 :(得分:2)

SELECT d.dpt_id, 
d.dpt_title, 
d.dpt_active, 
d.dpt_parent,
p.dpt_title AS parent_title
FROM tbl_department d
LEFT JOIN tbl_department p
    ON p.dpt_parent = d.dpt_id
ORDER BY d.dpt_title

答案 3 :(得分:1)

我认为这个查询需要重写为:

SELECT dpt_id,  
dpt_title,  
dpt_active,  
dpt_parent,  
    (SELECT dpt_title  
     FROM tbl_department AS [dept2]
     WHERE [dept2].dpt_id = [dept1].dpt_parent 
     ) AS parent_title 
FROM tbl_department AS [dept1] ORDER BY dpt_title 

否则SQL服务器将不知道您正在谈论的表的实例

答案 4 :(得分:1)

我认为你正在寻找类似的东西:

SELECT a.dpt_id, 
a.dpt_title, 
a.dpt_active, 
a.dpt_parent, 
b.dpt_title AS parent_title
FROM tbl_department AS a
INNER JOIN tbl_department AS b ON b.dpt_id = a.dpt_parent
ORDER BY dpt_title

答案 5 :(得分:0)

我认为解决方案是在同一个表上进行连接,或者您可以创建一个用户定义的函数,该函数获取部门ID并返回父部门名称。