我想运行一个查询来选择某些列,如果它们的名称包含字符串。 所以说我有列COL_1,COL_2,col_3,example_1,example_2我想运行:mysql - 如何根据名称选择列
SELECT example_1, example_2 FROM `table`
但模式匹配。所以:我好像
SELECT LIKE %`example_`% FROM `table`
无法找到如何在任何地方执行此操作
我想运行一个查询来选择某些列,如果它们的名称包含字符串。 所以说我有列COL_1,COL_2,col_3,example_1,example_2我想运行:mysql - 如何根据名称选择列
SELECT example_1, example_2 FROM `table`
但模式匹配。所以:我好像
SELECT LIKE %`example_`% FROM `table`
无法找到如何在任何地方执行此操作
您不能像使用通配符那样为列的值指定列的名称。你可以做的最好的方法是使用像php这样的服务器端语言来表达你的查询,并将变量作为列名。例如..
$query = 'select ' . $columnName1 . ', ' . $columnName2 . ' from myTable;';
您不能使用标准SQL。列名不被视为SQL中的数据。
如果您使用具有存储列名称,类型等的元数据表的SQL引擎,则可以在该表上选择。
您可以使用下面的查询得到同样的列名:
select * from information_schema.columns where table_name='table1' and column_name like 'a%'
林有点晚了这里,
事实上它可能与MySQL存储过程
DELIMITER //
create procedure custom_select()
begin
declare str_var TEXT;
select GROUP_CONCAT(column_name) into str_var from information_schema.columns where table_name ="YOUR_TABLE_NAME" and column_name like "example_%" and table_schema="YOUR_DATABASE";
set @q = CONCAT('select ', str_var, ' from table_name ');
prepare stm from @q;
execute stm;
end//
而且通过给他们打电话
delimiter ;
call custom_select();