Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres searching in a column splitted by regexp_split_to_table

I have the following table:

cs_id ; cs_values ; cs_desc
---------------------------
     1;    'a,b,c';   'one'
     2;      'd,a';   'two'
     3;      'a,c'; 'three'

The field "cs_valies" contains different comma separeted values. I would like to get all "cs_id" on lines that contain a certain value in "cs_values".

I used this expression:

SELECT
   cs_id,
   regexp_split_to_table(cs_values, '* , *') as splitted_value
WHERE
   splitted_value = 'a'

I have to questions:

  1. Postgres does not like alias names in the WHERE-clause. Or has anyone an idea how to achieve this?
  2. Does anyone have a better idea to solve the given problem?

Thanks everybody, I hope I am not missing something extremly evident.

like image 787
Richard Avatar asked Mar 29 '11 16:03

Richard


1 Answers

Postgres does not like alias names in the WHERE-clause. Or has anyone an idea how to achieve this?

SELECT * 
FROM (
   SELECT 
      cs_id,
      regexp_split_to_table(cs_values, '* , *') as splitted_value
) t
WHERE
   splitted_value = 'a'

Does anyone have a better idea to solve the given problem?

Normalize your table and put the "comma separated list" into its own table with. This is a classical 1:n relation

like image 123
a_horse_with_no_name Avatar answered Jan 01 '23 08:01

a_horse_with_no_name