简体   繁体   中英

Selecting from two tables with a same named column

SELECT bar.*, baz.foo FROM bar LEFT JOIN baz if I have a column called foo in bar, what is the standard SQL behaviour? Will the result set contain only foo from baz or...?

It will contain column foo from both tables.

Since your question is tagged 'standards', I would suggest using an explicit alias for 2 columns with the same name in a result set.

It will contain two output columns called foo ; one with values from table bar and one values from table baz .

If you do a natural join, then the foo columns will be used in the join and only one value will appear in the output - but you did a left outer join, not a natural join.

You do need to specify the join condition with an ON clause or a USING clause (but not every DBMS supports USING).

It will contain 2 x foo columns. This isn't a problem for SQL, but it tends to break client code. Simply alias it

SELECT bar.*, baz.foo AS foo2...
SELECT bar.*, foo2 = baz.foo...

While we're on standards, SELECT * isn't good practice: use named columns. It's been discussed to death already in other questions...

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