Search code examples
sqlmysqljoinsubquery

In SQL or MySQL, can we join a table and a subquery result?


Can we join a table with the result of a subquery, such as:

select name from gifts
    LEFT OUTER JOIN (select giftID from gifts) ...

If not, can it be done by some methods, such as creating a temporary table?

P.S. Can a subquery only appear using IN or NOT IN, or EXISTS or NOT EXISTS?


Solution

  • Yes, sql works on sets; a subquery returns a set as result, so this is possible.

    You have to give the subquery a name: (SELECT * FROM table) AS sub or (SELECT * FROM table) sub. As full query:

    SELECT name FROM gifts
        LEFT OUTER JOIN (SELECT giftID FROM gifts) AS sub
        ON ...
    WHERE ...