从嵌套选择中选择使用联接

时间:2018-08-13 18:58:57

标签: sql

用户向我发送了任意SQL(我对此有所了解,我知道它具有ID列),并且我需要能够过滤掉具有不同表中条目的记录。

我想做这样的事情

select * from (<user sql>) join t1 on t1.MemberID = ID where t1.Key = '12345'

这可行,但是我的结果集最终包含t1的所有列以及用户的列。我只想要用户提供的查询的列

1 个答案:

答案 0 :(得分:1)

我建议使用表别名和exists -仅选择所需的列:

select t.*
from (<user sql>) t
where exists (select 1 
              from t1 
              where t1.MemberID = t.ID and t1.Key = '12345'
             );

为什么exists?如果t1碰巧有重复项,则可以防止重复。