简体   繁体   中英

Subquery with multiple results, SQL Server

I have a query that looks like this:

SELECT * 
FROM dbo.document_library_file_attributes 
WHERE my_file_id=
(SELECT my_file_id 
 FROM dbo.document_library_file_attributes 
 WHERE attribute_name='Directory/Key' AND attribute_value LIKE @directory+'%')

I want to the subquery to be able to return multiple results, meaning my_file_id could equal 'directoryA', 'directoryB', and I want the results for all of these. How would I do that?

Use IN instead of = for result sets:

SELECT * 
FROM dbo.document_library_file_attributes 
WHERE my_file_id IN
(SELECT my_file_id 
 FROM dbo.document_library_file_attributes 
 WHERE attribute_name='Directory/Key' AND attribute_value LIKE @directory+'%')

It:

Determines whether a specified value matches any value in a subquery or a list.

I think a JOIN is a better way to express what you're trying to do:

SELECT DISTINCT lfa2.* 
FROM 
    dbo.document_library_file_attributes lfa
    JOIN dbo.document_library_file_attributes lfa2
        ON lfa.my_file_id = lfa2.my_file_id 
WHERE 
    lfa.attribute_name='Directory/Key' 
    AND lfa.attribute_value LIKE @directory+'%'

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