且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Mysql查询在表的所有列中搜索一个字符串

更新时间:2023-11-26 22:10:10

以下是连接动态 SQL 中的值的方法:

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;

当然,动态 SQL 并不是特别便携.这个想法适用于大多数数据库.代码看起来会有所不同.

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

此处进行测试和工作.

最后,您可以使用变量替换(这是更好的方法)来做到这一点:

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;

也测试过(;-).