SQL在同一个表中加入混淆

时间:2016-06-30 07:52:24

标签: sql-server

我有一张这样的表

enter image description here

;WITH People AS 
(
    SELECT 1 as id, 'Ahanda' as name, 20000 as salary, 3 as manager_id
    UNION ALL
    SELECT 2, 'Mahfuj', 30000, 4
    UNION ALL
    SELECT 3, 'Mr. John', 15000, NULL
    UNION ALL
    SELECT 4, 'Mr. Tom', 18000, NULL
)

现在我想要这种类型的输出找到有经理的人的名字,而他的经理的薪水超过17000。

我尝试过这个SQL

SELECT P.name 
FROM People P 
INNER JOIN People Q ON P.id = Q.manager_id
WHERE Q.salary >= 17000

但答案是

enter image description here

但是从表的值来看,它只是People表的第2行,答案是Mahfuj

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:4)

得到错误的方法,你的联接有逻辑倒退。您希望将表'P'中的经理ID加入表'Q'的id

SELECT 
P.name 
FROM  People P 
INNER JOIN People Q 
ON P.manager_id = Q.id
WHERE q.salary>=17000

P.S。我喜欢经理人的报酬低于员工。

答案 1 :(得分:3)

您需要更改查询,如下所示:

SELECT P.name FROM People P INNER JOIN People Q ON P.manager_id = Q.id WHERE Q.salary >= 17000

答案 2 :(得分:1)

试试这个,

SELECT P.NAME
FROM People P
INNER JOIN People Q ON P.manager_id = Q.ID
WHERE Q.salary >= 17000

答案 3 :(得分:1)

只需更改JOIN语句:

SELECT P.name 
FROM People P 
INNER JOIN People Q 
    ON Q.id = P.manager_id
WHERE Q.salary>=17000

输出:

name
Mahfuj