Unfortunately, no; there is no SQL syntax for ensuring that column names are unique.
If you truly don't know the names of the columns and must use SELECT *
, your only real option would be to revert to some very ugly looking dynamic SQL that could inspect the structure of the tables and generate a query that would select them all explicitly with a table-name prefix.
I don't know which RDBMS you're using, but something like this should work on SQL Server:
declare @columns table (idx int identity(1,1), tablename varchar(100), columnname varchar(100))
insert into @columns (tablename, columnname)
select tablename, columnname
from INFORMATION_SCHEMA.COLUMNS
where tablename in ('table_1', 'table_2')
declare @sql nvarchar(4000)
declare @i int
declare @cnt in
declare @col varchar(100)
declare @table varchar(100)
select @i = 0, @cnt = max(idx), @sql = '' from @columns
while @i < @cnt
begin
select @i = @i + 1
select @col = columnname, @table = tablename from @columns where idx = @i
if len(@sql) > 0
select @sql = @sql + ', '
select @sql = @sql + '[' + @table + '].[' + @col + '] as [' + @table + '_' + @col + ']'
end
select @sql = 'select ' + @sql + ' from table_1, table_2'
exec sp_executesql @sql