如何在某些条件下从SQL中的其他表中获取行?

时间:2018-05-04 07:15:54

标签: sql sql-server

我有两张桌子: tbl_AliedMastertbl_PlantMaster

tbl_AliedMaster的结构如下:

Id  Empid       Name            Mobile          Email           Designation
----------------------------------------------------------------------------------
1   UBM1001     John            1211567890      john@a.com          UBM
2   TSM1001     Root            1212121212      root@a.com          TSM
3   PI2         Billy           7862653222      billy@a.com         PI
4   PI6         YongLee         1452369872      lee@a.com           PI

tbl_PlantMaster的结构如下:

Plantid     plantcode   FSEID
--------------------------------
1           NS01        UBM1001
2           NS01        TSM1001
3           NS09        PI2
4           NS01        PI6

FSEID plantmaster Empid映射到AliedMaster表的UBM 当我选择TSM Empid时,我希望收到指定plantcodeEmpid的电子邮件。 这适用于PI6 John,我希望收到Rootplant code的电子邮件,因为它们共享相同的SELECT Email from tbl_AliedMaster Where designation like '%UBM%' and Empid IN (SELECT FSE_Empid FROM tbl_PlantMaster WHERE FSE_Empid = 'PI6') 。 这是我尝试过的:

sudo chmod 700 ~/.ssh
sudo chmod 600 ~/.ssh/authorized_keys

我知道这是错的,没有给我预期的结果。我通过匹配那些工厂代码但是与用户匹配来尝试其他查询,但是失败了。 任何帮助,将不胜感激。谢谢!

4 个答案:

答案 0 :(得分:1)

您需要获得所有empid关注植物代码

SELECT  Email
from tbl_AliedMaster
Where designation like '%UBM%'
  and Empid IN (SELECT FSE_Empid FROM tbl_PlantMaster WHERE plantcode = 'NS01')

OR

SELECT  Email
from tbl_AliedMaster
Where designation like '%UBM%'
  and Empid IN 
   (SELECT FSE_Empid FROM tbl_PlantMaster WHERE plantcode IN 
     ( SELECT plantcode  FROM tbl_PlantMaster WHERE FSE_Empid = 'PI6'))

答案 1 :(得分:1)

试试这个

SELECT  Email
from tbl_AliedMaster
Where 
 Empid IN ( select FSEID from tbl_PlantMaster where designation like '%UBM%' and plantcode in ( SELECT plantcode  FROM tbl_PlantMaster WHERE FSE_Empid = 'PI6'))

答案 2 :(得分:0)

我没有尝试过,但我认为这应该有效

select email.tbl_AliedMaster from tbl_AliedMaster,tbl_PlantMaster Where designation like '%M' and Id.tbl_AliedMaster=Plantid.tbl_PlantMaster Group by plantcode.tbl_PlantMaster Having count(*)<1; 

答案 3 :(得分:0)

你可以用两种方式做到这一点。

使用子查询

 SELECT DISTINCT A.email
 FROM tbl_AliedMaster A
 WHERE A.Designation LIKE '%UBM%'
 AND EXISTS (SELECT 1 FROM tbl_PlantMaster B WHERE A.Empid=B.FSEID);

OR

加入

 SELECT DISTINCT A.email
 FROM tbl_AliedMaster A INNER JOIN tbl_PlantMaster B ON A.Empid=B.FSEID
 WHERE A.Designation LIKE '%UBM%';