首页 > 解决方案 > 使用连接从嵌套选择中选择

问题描述

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

即我想做这样的事情

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

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

标签: sql

解决方案


我建议使用表别名和exists-- 并且只选择你想要的列:

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

为什么exists?如果t1碰巧有任何重复,这可以防止重复。


推荐阅读