简体   繁体   English

MySQL - 在 select 内选择并使用 NOT EXISTS

[英]MySQL - select inside select and use NOT EXISTS

I have these tables:我有这些表:

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

Dapartments(Name text, Manger text)

And I want to get the name of an employee who has only one manager, I guess there are a total of 2 managers, and each employee can have 2 managers (at least 1).而且我想得到一个只有一个经理的员工的名字,我猜一共有 2 个经理,每个员工可以有 2 个经理(至少 1 个)。

I try to do:我尝试做:

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');

And I get this error:我收到这个错误:

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

What is wrong here?这里有什么问题?

Thanks谢谢

You need an table alias name for the FROM( ) Table_name _alias ( in this sample T)您需要 FROM() Table_name _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'
        );

One way is below:一种方法如下:

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
           )

--- If only Worker Name is required then: --- 如果只需要工人姓名,则:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM