简体   繁体   中英

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.

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

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 ?

(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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM