MySQL-在内部选择并使用“不存在”

时间:2019-02-25 19:39:03

标签: mysql sql

我有这些表:

WORKERS(Id integer PRIMARY KEY, Name text, Phone text, Age integer, Dapartment 
text)

Dapartments(Name text, Manger text)

我想得到一个只有一名经理的员工的名字,我想总共有2名经理,每个员工可以有2名经理(至少1名)。

我尝试做:

SELECT Name, 
       Manger 
  FROM (SELECT * 
          FROM WORKERS 
               INNER JOIN Dapartments 
                  ON WORKERS.Dapartment = Dapartments.Name 
         WHERE Manger = 'manger1') 
 WHERE NOT EXSITS (SELECT * 
                     FROM WORKERS 
                         INNER JOIN Dapartments 
                            ON WORKERS.Dapartment = Dapartments.Name 
                    WHERE Manger = 'manger2');

我收到此错误:

Error: near line 52: near "SELECT": syntax error

这是怎么了?

谢谢

2 个答案:

答案 0 :(得分:1)

您需要FROM()表名_alias的表别名(在此示例T中)

    SELECT T.Name, 
           T.Manger 
    FROM (
        SELECT * 
        FROM WORKERS 
        INNER JOIN Dapartments ON WORKERS.Dapartment = Dapartments.Name 
        WHERE Manger = 'manger1'
        )  T 
     WHERE NOT EXSITS (
        SELECT * 
        FROM WORKERS 
        INNER JOIN Dapartments ON WORKERS.Dapartment = Dapartments.Name 
        WHERE Manger = 'manger2'
        );

答案 1 :(得分:0)

下面是一种方法:

Select w.Name ,d.Manger 
    From Dapartments d
    Join Workers w
    On W.Dapartment = D.Name
Where w.id in (  
Select Id, --count(Dapartment) As Mangrs 
From WORKERS 
group by Id 
Having count(Dapartment)=1
           )

---如果仅需要工人名称,则:

 Select t.Name As Single_Mgr_Worker 
From (
Select Name, count(Dapartment) As Mangrs 
From WORKERS 
group by Id 
Having count(Dapartment)=1
           ) t