简体   繁体   中英

Filtering Column based on values on Another table

I'am tying to get the specific columns whose name starts with some patterns.

table_1

abcA| abcB | abcC | xyD | mnE

1 | 2 | 3 | 4 | 5

6 | 7 | 8 | 9 | 10

11 | 12 | 13 | 14 | 15

From the above table i'am in need of the Output Like

abcA | abcB | abcC

1 | 2 | 3

6 | 7 | 8

11 | 12 | 13

The columns should be selected DYNAMICALLY by filtering like any column name starts with abc should me selected.

I Tried this Query

"select column_name from information_schema.columns 
where table_name='table_1' and column_name like 'abc%';"

It gives a another table only with column names

column_name

abcA

abcB

abcC

But I want to get the values of that Column names.

Thanks

This is poor table design, and it is fairly difficult to write code which can select a dynamic column name. Here is the design I would suggest to you:

ID  | name | pos
1   | abcA | 1
2   | abcB | 1
3   | abcC | 1
4   | xyD  | 1
5   | mnE  | 1
6   | abcA | 2
7   | abcB | 2
8   | abcC | 2
9   | xyD  | 2
10  | mnE  | 2
11  | abcA | 3
12  | abcB | 3
13  | abcC | 3
14  | xyD  | 3
15  | mnE  | 3

With this design in place, you only need a very simple query:

SELECT pos, GROUP_CONCAT(ID) AS ids
FROM yourTable
WHERE name LIKE 'abc%'
GROUP BY pos;

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