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

22,403

Solution 1

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

Solution 2

yes you can use a select as an INNER JOIN you just have to give it an alias:

SELECT Name FROM Transactions T
INNER JOIN (SELECT Distinct customerID As CustomerID FROM Customers) A 
ON A.CustomerID = T.CustomerID

Solution 3

Another way, could be to create a VIEW of the subquery. Then do a JOIN as you would normally would (by referencing the VIEW).

Solution 4

SELECT CustomerId,
       Name,
       Address
FROM Table1 M
INNER JOIN Table2 C ON M.CustomerId=C.CustomerId
WHERE CustomerId IN
    (SELECT CustomerId
     FROM Table1 M
     INNER JOIN Table2 ON M.CustomeID=C.CustomerId)
ORDER BY CustomerId,
         Name,
         Address
Share:
22,403
nonopolarity
Author by

nonopolarity

I started with Apple Basic and 6502 machine code and Assembly, then went onto Fortran, Pascal, C, Lisp (Scheme), microcode, Perl, Java, JavaScript, Python, Ruby, PHP, and Objective-C. Originally, I was going to go with an Atari... but it was a big expense for my family... and after months of me nagging, my dad agreed to buy an Apple ][. At that time, the Pineapple was also available. The few months in childhood seem to last forever. A few months nowadays seem to pass like days. Those days, a computer had 16kb or 48kb of RAM. Today, the computer has 16GB. So it is in fact a million times. If you know what D5 AA 96 means, we belong to the same era.

Updated on July 09, 2022

Comments

  • nonopolarity
    nonopolarity almost 2 years

    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?