0

I have many columns which are of the form: rp_id_1 rp_id_2 and so on. I want to get data for these specific columns. On the forum I see below type of query being suggested:

"SELECT column_name
FROM information_schema.columns
WHERE table_name='loc_tbl'
AND column_name LIKE 'rp%'"

However this only returns the column names and not the data. Output:

+-------------+
| column_name |
+-------------+
| rp_id_1     |
| rp_id_2     |
| rp_id_3     |

What am I missing? How do I get the data for all these columns instead? Thanks.

3
  • use * instead of column_name Commented Oct 26, 2018 at 6:51
  • Tried that. It returns data from the information_schema.columns table instead. Commented Oct 26, 2018 at 6:53
  • You are going to need dynamic SQL to do this. Commented Oct 26, 2018 at 6:55

1 Answer 1

2

We can do this using dynamic MySQL. From the MySQL command line:

SELECT @cols := GROUP_CONCAT(column_name) FROM information_schema.columns
    WHERE table_name = 'loc_tbl' AND column_name LIKE 'rp%';
SET @query = CONCAT("SELECT ", @cols, " FROM lob_tbl");
PREPARE stmt FROM @query;
EXECUTE stmt;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.