Sql 检查临时表中是否存在一对多结果

Sql 检查临时表中是否存在一对多结果,sql,sql-server,tsql,stored-procedures,Sql,Sql Server,Tsql,Stored Procedures,如何检查一对多表在临时表中是否包含一个或多个结果 @colors Temp Table ------ Red Blue Green Pink Yellow SELECT u.userID, u.color FROM USERS as u WHERE u.field = '123' AND ( (SELECT t2.userColor FROM TABLE2 as t2 WHERE t1.userID = u.userID) IN

如何检查一对多表在临时表中是否包含一个或多个结果

@colors Temp Table
------
Red
Blue
Green
Pink
Yellow


SELECT 
    u.userID,
    u.color
FROM 
    USERS as u
WHERE 
    u.field = '123'
AND
    (
        (SELECT t2.userColor FROM TABLE2 as t2 WHERE t1.userID = u.userID) IN (SELECT color FROM @colors)
    )
在这种情况下,表2包含一个或多个结果,例如用户的红色和绿色。我需要能够查看临时表中是否存在这两种情况


简而言之,从表2中选择t2.userColor作为t2,其中t1.userID=u.userID可以包含用户的一个或多个记录,我需要查看临时表中是否存在这些颜色。

简单使用交叉/外部应用:

SELECT 
    u.userID,
    u.color,
    [tmpColors].[count]
FROM 
    USERS as u
outer apply
(select count(1) as [count] from Table2 t join @colors c on c.color = t.userColor where t.userId = u.userId) as [tmpColors]
WHERE 
    u.field = '123'

我认为最简单的方法是使用exists,因为我没有得到您返回任何匹配颜色信息所需的印象

SELECT u.userID, u.color
FROM USERS as u
WHERE u.field = '123'
AND EXISTS (
    SELECT t.userColor
    FROM TABLE2 AS t INNER JOIN @colors AS c ON c.color = t.userColor
    WHERE t.userID = u.userID
    );

这毫无意义。你能发布一些实际的细节吗?像ddl表和示例数据?我不知道为什么有人决定投这一票。