[英]T-SQL Select columns from one table where id in another table
I asked this question some time back: Adding attachments to taks records in T_SQL and got a perfect answer to my question. 不久前 ,我问了这个问题: 在T_SQL的Taks记录中添加附件,并很好地回答了我的问题。
However I need to take this one step further. 但是,我需要更进一步。 If I have the following (based on the previous question's answer) 如果我有以下内容(基于上一个问题的答案)
SELECT TaskId, TaskDescription, TaskType
FROM Tasks
WHERE TaskType = 1 [FIRST-TABLE]
I want be able to then select 我希望能够然后选择
SELECT AttachmentId, TaskId, [FileName], FileLocation
FROM TaskAttachments
[WHERE TaskId IN FIRST-TABLE] ;
and I need to be able to return both tables to asp.net 而且我需要能够将两个表都返回到asp.net
I can write a query which does this: 我可以编写一个查询来做到这一点:
SELECT AttachmentId, TaskId, [FileName], FileLocation
FROM TaskAttachments
WHERE TaskId EXISTS IN (SELECT TaskId, TaskDescription, TaskType
FROM Tasks
WHERE TaskType = 1);
My actual queries are much longer with lots of joins and so this second query becomes very long and this seems convoluted and requires selecting the same data twice. 我的实际查询需要很多连接,因此需要更长的时间,因此第二个查询变得很长,而且看起来很复杂,需要两次选择相同的数据。
Is there a better way than this by using the actual data returned from the first SELECT
? 通过使用从第一个SELECT
返回的实际数据,有没有比这更好的方法了?
(BTW, please forgive any syntax errors. This is just for quick illustration, my actual code works fine!!) (顺便说一句,请原谅任何语法错误。这只是为了快速说明,我的实际代码工作正常!!)
You can use common table expression in this situation: 在这种情况下,您可以使用公用表表达式:
;with cte as(SELECT TaskId, TaskDescription, TaskType FROM Tasks)
SELECT AttachmentId, TaskId, [FileName], FileLocation
FROM TaskAttachments where TaskID in(select TaskId from cte where TaskType = 1)
EDIT: 编辑:
IF EXISTS(SELECT * FROM tempdb.sys.tables WHERE [name] = '#tasks') BEGIN
DROP TABLE #tasks;
END;
--save to temp table
SELECT TaskId, TaskDescription, TaskType into #tasks FROM Tasks
--select from temp table
SELECT TaskId, TaskDescription, TaskType FROM #tasks
--select from second table using temp table
SELECT AttachmentId, TaskId, [FileName], FileLocation
FROM TaskAttachments where TaskID in(select TaskId from #tasks where TaskType = 1)
Joining the two tables perhaps instead of using an EXISTS clause? 联接两个表也许不是使用EXISTS子句?
SELECT ta.AttachmentId, ta.TaskId, ta.FileName, ta.FileLocation
FROM TaskAttachments ta INNER JOIN Tasks t ON ta.TaskId = t.TaskId
WHERE t.TaskType = 1;
That would result in a shorter query. 这将导致查询缩短。
SELECT AttachmentId, TaskAttachments.TaskId, [FileName], FileLocation
FROM TaskAttachments
JOIN Tasks
on TaskAttachments.TaskId = Tasks.TaskId
and Tasks.TaskType = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.