简体   繁体   English

MySQL选择列名称包含子字符串的列

[英]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. recommendation_1_name ”,“ recommendation_1_company ”,“ recommendation_1_contact ”,“ recommendation_2_name ”,“ recommendation_2_company ”,“ recommendation_2_contact ”等。

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. 我将一个excel文件导入到表中,所以它只是一个大表。

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%'. 该查询为您动态生成一个带有“ recommendation%”之类的所有字段的SELECT查询。 You only must setup the Databasename, and the Tablename. 您只需设置数据库名称和表名称。 You can directly query the result of my query or add the WHERE clause. 您可以直接查询我的查询结果或添加WHERE子句。

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. 不要忘记用您的真实数据库名称替换TABLE_SCHEMA = 'test'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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