获取以substring开头的列的内容

时间:2017-02-02 14:17:34

标签: mysql sql

我有一个具有以下结构的表:

| ID | abc1   | abc2   | abc3   | def1   | def2   | def3   |
|----|--------|--------|--------|--------|--------|--------|
| 1  | Text 1 | Text 2 | Text 3 | Text A | Text B | Text C |
| 2  | Text 4 | Text 5 | Text 6 | Text D | Text E | Text F |

我现在想要获取以abc开头的所有列的内容。

select column_name from information_schema.columns 
where table_name='tab1'
and (column_name like 'abc%')

我得到了所需的列:

abc1
abc2
abc3

我怎样才能获得他们的内容?所以期望的输出是:

| abc1   | abc2   | abc3   |
|--------|--------|--------|
| Text 1 | Text 2 | Text 3 |
| Text 4 | Text 5 | Text 6 |

我的方法是将该查询放在另一个查询中,如:

select (select column_name from information_schema.columns 
where table_name='tab1'
and (column_name like 'abc%'))
from tab1

但是我收到了这个错误:

Subquery returns more than 1 row

1 个答案:

答案 0 :(得分:1)

如评论中所述,您需要动态SQL来从所选列中获取值。

--get the column names in a comma separated format
SELECT GROUP_CONCAT(COLUMN_NAME)
INTO @COLS --variable that holds the columns
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME =  'tab1'
AND COLUMN_NAME LIKE 'abc%';

SET @TBL= 'tab1';

SET @S= CONCAT('select ',@COLS, ' from ', @TBL);

PREPARE STMT FROM @S;

EXECUTE STMT;

DEALLOCATE PREPARE STMT;

Sample Demo