简体   繁体   中英

MySQL Select columns where the column name contains a substring

I have a table with a lot of fields about a person and then several recommendations of other people.

They are named:

" recommendation_1_name " " recommendation_1_company " ' recommendation_1_contact " " recommendation_2_name " " recommendation_2_company " " recommendation_2_contact " and so on.

I am trying to come up with a statement that allows me to only get the recommendations.

I imported an excel file into the table so it's just one large table.

This is what I have and it is returning an Empty set.

select * from questionnaire where 'COLUMN_NAME' like '%recommendation%';

I've been playing around with it making a table with only the recommendation fields and it still doesn't return anything.

Mysql:从(表)中选择“ commentation_1_name”,“ commentation_2_name”等...,其中(USER)=(USERID),或者您可以唯一地标识该用户。

This Query generates you dynamic a SELECT query with all fields like 'recommendation%'. You only must setup the Databasename, and the Tablename. You can directly query the result of my query or add the WHERE clause.

SELECT 
  CONCAT( 'SELECT ',
    GROUP_CONCAT(COLUMN_NAME SEPARATOR ',\n')
  )
  FROM information_schema.columns 
  WHERE TABLE_SCHEMA = 'DBNAME' 
  AND TABLE_NAME = 'TABLENAME' 
  AND COLUMN_NAME LIKE 'recommendation%';

You really need to normalize your schema.

But just as an experiment and example for some other cases (maybe somebody really need it). Here is solution to get this case resolved using stored procedure:

CREATE PROCEDURE `get_recommendations`()

BEGIN
DECLARE Q VARCHAR(100);
DECLARE C_NAME VARCHAR(100);
DECLARE cur CURSOR FOR SELECT GROUP_CONCAT(column_name) as `columns`
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = 'test' 
  AND TABLE_NAME ='questionnaire'
  AND COLUMN_NAME LIKE  '%recommendation%'
;

SET Q  = 'SELECT ';

OPEN cur;
   FETCH cur INTO C_NAME;
   SET Q = CONCAT(Q,C_NAME,' ');
CLOSE cur;

SET @Q = CONCAT(Q,'FROM questionnaire;');

 PREPARE stmt FROM @Q;
 EXECUTE stmt ;

END

Don't forget to replace TABLE_SCHEMA = 'test' with your real database name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM