如何在连接表中选择具有所有匹配条件的表中的行

时间:2017-10-17 03:13:56

标签: sql sql-server tsql

我有两个表(表A)和(表B)以及一个表变量(@country),它们将构建where条件以查找与国家/地区匹配的员工列表。

TableA(empId,name)

(1,约翰),(2,玛丽),(3,哈利)

表B(empId,国家/地区)

(1,澳大利亚),(1,US),(1,UK),(2,US)

例如,我只需要选择TableA中居住在澳大利亚和美国的员工。即emp 1(约翰)。如果需要,查询应该能够在where子句中处理更多国家/地区。这取决于表变量@country中的国家/地区数量。

我尝试了很多选项,包括以下查询,但似乎没有任何效果。

 DECLARE @country TABLE (
        [country]   [nvarchar](255) NOT NULL
 );

 insert into @country (country) values('Australia'),('US')

Select E.empID, EC.empID,EC.country from TableA E
INNER JOIN  TableB EC on E.empID= EC.empID
Where EC.country = ALL(Select country from @country)

请问您如何编写最佳查询来完成此任务?请注意,@ country可以有一个或多个国家。

3 个答案:

答案 0 :(得分:0)

尝试:

SELECT E.empID
    ,EC.empID
    ,EC.country
FROM TableA E
INNER JOIN TableB EC
    ON E.empID = EC.empID
WHERE EXISTS (
        SELECT 1 
        FROM TableB EC_US
        WHERE EC_US.empID = EC.empID
            and EC_US.Country = 'US'
    )
    AND EXISTS (
        SELECT 1 
        FROM TableB EC_Aus
        WHERE EC_Aus.empID = EC.empID
            and EC_Aus.Country = 'Australia'
    )

或者:

SELECT E.empID
    ,EC.empID
    ,EC.country
FROM TableA E
INNER JOIN TableB EC
    ON E.empID = EC.empID
WHERE EC.empID IN (
        SELECT EC_Sub.empID
        FROM TableB EC_Sub
        WHERE EC_Sub.Country IN ('Australia','US')
        GROUP BY EC_Sub.empID
        HAVING COUNT(*) = 2
    )

答案 1 :(得分:0)

立即尝试,添加where子句。更改@country的任何值并执行查询:

DECLARE @TableA TABLE (empId INT, [Name] VARCHAR(100))

INSERT INTO @TableA VALUES (1, 'John')
INSERT INTO @TableA VALUES (2, 'Mary')
INSERT INTO @TableA VALUES (3, 'Harry')

DECLARE @TableB TABLE (empID INT, country VARCHAR(100))

INSERT INTO @TableB VALUES (1, 'Australia')
INSERT INTO @TableB VALUES (1, 'UK')
INSERT INTO @TableB VALUES (2, 'US')


 DECLARE @country TABLE ([country] [nvarchar](255) NOT NULL);

 INSERT INTO @country (country) VALUES('Australia'),('US')

SELECT a.* , tb.country
FROM   @TableA AS a
       INNER JOIN (
                SELECT b.empid,
                       COUNT(*)  AS empInMultipleCountry
                FROM   @TableB      b   
                GROUP BY
                       empid
            ) b
            ON  a.empId = b.empid
     INNER JOIN @TableB AS tb
            ON tb.empId = a.empId

WHERE  empInMultipleCountry > 1
AND EXISTS (SELECT 1 FROM @country AS c WHERE c.country = tb.country)

答案 2 :(得分:-1)

Select E.empID, EC.empID,EC.country 
from TableA E INNER JOIN TableB EC on E.empID= EC.empID
Where EC.country IN ('Australia','US');