Search code examples
sqlsql-server-2008sql-optimization

how to optimize several "WHERE (Select .... ) = value" from same table


It's hard to compose a topic name for me. But I can show an example :

WHERE   (SELECT [ID_Line] FROM [Event] WHERE [Event].[Name]  = [A].[Col]) = 2
AND     (SELECT [DataType] FROM [Event] WHERE [Event].[Name]  = [A].[Col]) = 2

Here I'm processing 2 queries when I really need something like that :

WHERE   (SELECT [ID_Line],[DataType] FROM [Event] WHERE [Event].[Name]  = [A].[Col]) = 2,2

but SQL doesn't work with tuples, so must I make Inner Join here ?


Solution

  • you can try something like this :

    WHERE EXISTS (
        SELECT [ID_Line] FROM [Event] WHERE
            [Event].[Name]  = [A].[Col] AND
            [Event].[ID_Line] = 2 AND
            [Event].[DataType] = 2
    )
    

    If you provide more information about the complete query and your database structure, a more precise answer could be given. It is possible that this isn't the best solution.