Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting column using REGEXP in MySQL

So I have a table with many columns. Suppose that each column contains similar keywords, differing only by a few. I want to select these columns based on their similar keywords.

At first, this was my try:

SELECT * REGEXP 'pages_title$' FROM 'pages';

That is, any column that ends with pages_title should be selected. So the REGEXP should apply to the column's name, not any entries. Is this possible? All of the examples I have found online pertain to using REGEXP to isolate certain values within the table, which isn't what I want.

like image 627
id2341677 Avatar asked Sep 16 '11 21:09

id2341677


People also ask

What does REGEXP do in MySQL?

MySQL REGEXP performs a pattern match of a string expression against a pattern. The pattern is supplied as an argument. If the pattern finds a match in the expression, the function returns 1, else it returns 0. If either expression or pattern is NULL, the function returns NULL.

What is regular expressions REGEXP in SQL?

A Regular Expression is popularly known as RegEx, is a generalized expression that is used to match patterns with various sequences of characters. A RegEx can be a combination of different data types such as integer, special characters, Strings, images, etc.

Does MySQL like use RegEx?

Use the LIKE or NOT LIKE comparison operators instead. The other type of pattern matching provided by MySQL uses extended regular expressions. When you test for a match for this type of pattern, use the REGEXP_LIKE() function (or the REGEXP or RLIKE operators, which are synonyms for REGEXP_LIKE() ).


1 Answers

This isn't a complete answer but it might get something rolling. You can build your query dynamically:

declare @q varchar(1000)
set @q = 'select ' + @columnName + ' from table'
EXEC(@q)

Otherwise, you could get a selected set of column names from a table like so (MS T-SQL):

select name from DB.sys.syscolumns 
where id=(
    select id 
    from DB.sys.sysobjects 
    where xtype='U' 
    and name='pages'
) 
where name LIKE '%pages_title'

Not sure how to use this set to query your table for a specific set of columns. Perhaps you could combine these two approaches somehow?

like image 62
Jonathan Wilson Avatar answered Oct 03 '22 23:10

Jonathan Wilson