Mysql query search a string in all columns of a table

后端 未结 4 1404
一向
一向 2021-01-27 11:43

I wonder how I can mount a SQL as portable as possible to query for all columns of a table for a specific phrase, like:

Table

ID | Name          


        
4条回答
  •  感动是毒
    2021-01-27 12:37

    Here is how you would concatenate the values in dynamic SQL:

    set @Pattern = '%augusto%';
    
    select @q := concat('select * from Table1 ',
                       'where concat(', group_concat(column_name), ', "") like "', @Pattern, '"'
                       )
    from information_schema.columns c
    where table_name = 'Table1';
    
    prepare st from @q;
    execute st;
    
    deallocate prepare st;
    

    Of course, dynamic SQL is not particularly portable. The idea would work in most databases. The code would look different.

    Tested and working here.

    And finally, you can do this with variable substitution (which is the better approach):

    select @q := concat('select * from Table1 ',
                       'where concat(', group_concat(column_name), ', "") like ?'
                       )
    from information_schema.columns c
    where table_name = 'Table1';
    
    set @p = '%augusto%';
    
    prepare st from @q;
    execute st using @p;
    
    deallocate prepare st;
    

    Also tested (;-).

提交回复
热议问题