SQL Select * from multiple tables

前端 未结 5 1730
[愿得一人]
[愿得一人] 2020-12-05 15:35

Using PHP/PDO/MySQL is it possible to use a wildcard for the columns when a select is done on multiple tables and the returned array keys are fully qualified to avoid column

5条回答
  •  时光说笑
    2020-12-05 16:01

    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
    

提交回复
热议问题