MySQL wildcard in select

徘徊边缘 提交于 2019-12-29 08:15:32

问题


Is there any way to select columns with wild cards.

like

to select columns with names having type could be 'SELECT %type% from table_name' ?


回答1:


Not really. You can use the * column wildcard to select all columns. If you're joining multiple tables, you can select all columns from specific table by prefixing * with the table name or alias:

SELECT a.id, a.title, b.*
  FROM articles AS a
    JOIN blurbs AS b ON a.id = b.article

However, you shouldn't use * unless you're writing a DB administration program.

Alternatively, you can build a statement within SQL or another language by fetching table metadata to get the column names. Using just MySQL, you can query the COLUMNS table in the INFORMATION_SCHEMA database to get the column names and use GROUP_CONCAT to build the column list for the statement.

SELECT CONCAT(
      'SELECT ',
      GROUP_CONCAT(COLUMN_NAME SEPARATOR ', '),
      ' FROM ', :db, '.', :table,
      ' WHERE ...'
      )
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA=:db AND TABLE_NAME=:table

Replace ":db", ":table" and "..." with the appropriate values. You can even turn it into a prepared statement so you can use it for any table. From there, PREPARE and EXECUTE the constructed statement.

If you're not limited to SQL for programming, it should be less messy. The DB driver for your language of choice likely offers methods to get metadata. The actual implementation would be similar to the pure SQL approach (get column names, assemble statement, prepare, execute), but shouldn't be so ugly, as you'd be using an algorithmic, rather than declarative, language.

I would be very interested in seeing the situation that this is actually required..




回答2:


You can find all fields that contains type within the name using the information_schema and then using prepared statement.

set @str = (concat('select ',(select concat(group_concat(column_name),' from ',table_name)
from information_schema.columns
where table_schema = 'your_db_name' and table_name = 'your_table_name' and column_name like '%type%')));
prepare stmt from @str;
execute stmt;
deallocate prepare stmt;



回答3:


Certainly possible if you are using a front-end language. If php just use

 $fieldlist= "cola, colb ";
 $tablename="tabl";
"select $fieldlist from $table"

My intuition is telling you are doing something simple using php-mysql but I may be wrong.



来源:https://stackoverflow.com/questions/5582144/mysql-wildcard-in-select

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!