如何根据第一个表中的行数显示第二个表中的位置名称?

时间:2017-11-11 19:37:30

标签: mysql sql

我有两张桌子"员工"和"职位"

我想写一个查询,显示表格中最少出现的位置名称"员工"我有外键" ID_of_Position"在"员工"。 我想出了类似的东西,但它可能不起作用:

SELECT Employees.ID_of_Position, Positions.ID_of_Position, Positions.Name_of_Position  
FROM Positions
WHERE Employees.ID_of_Position in (SELECT ID_of_Position
                                   FROM Employees
                                   GROUP BY ID_of_Position
                                   HAVING COUNT(ID_of_Position
                                  )=1)
INNER JOIN Employees ON Positions.ID_of_Position = Employees.ID_of_Position;

2 个答案:

答案 0 :(得分:1)

正确的语法如下:

SELECT e.ID_of_Position, p.ID_of_Position, p.Name_of_Position  
FROM Positions p JOIN
     Employees e
     ON p.ID_of_Position = e.ID_of_Position
WHERE e.ID_of_Position in (SELECT ID_of_Position
                           FROM Employees
                           GROUP BY ID_of_Position
                           HAVING COUNT(ID_of_Position) = 1
                          );

这不回答问题(除非有一个职位只有一名员工),但它至少在语法上是正确的。

请务必了解SELECT语句中的FROMWHERESELECT都是子句JOINFROM子句中的运算符。

答案 1 :(得分:0)

至少在加入后应该在哪里,并且最后有一些带括号的东西......

        SELECT Employees.ID_of_Position, Positions.ID_of_Position, Positions.Name_of_Position  
        FROM Positions
        INNER JOIN Employees ON Positions.ID_of_Position = Employees.ID_of_Position;
        WHERE Employees.ID_of_Position in (SELECT ID_of_Position
                                           FROM Employees
                                           GROUP BY ID_of_Position
                                           HAVING COUNT(ID_of_Position)=1
)