简体   繁体   中英

SQL Join result table as alias

Is there a way to give a result table of a join an alias?

Example query:

SELECT *
FROM t1
JOIN t2
ON t1.num = t2.num
AS result;

Yes!

select result.* 
from (SELECT *
    FROM t1
    JOIN t2
    ON t1.num = t2.num) result

You do need to watch where you've got columns of the same name in both the inner tables; you'll get an ambiguous column error for num in the results table. Instead of select * its a good idea to pick out the ones you want.

You can make it a table expression (sub-query) and give that an alias, but in your simple example I don't see what benefit it could add. I assume you're going to use this in a more complex query

SELECT *
FROM (
    SELECT t1.id, t1.name, t2.category, t2.subcategory
    FROM t1
    INNER JOIN t2 ON t1.id=t2.id
) AS result
LEFT JOIN t3 ON result.id=t3.id
SELECT result.* FROM 
(SELECT *
FROM t1
JOIN t2
ON t1.num = t2.num) AS result;

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