Array of arrays in PostgreSQL

前端 未结 3 845
一个人的身影
一个人的身影 2020-12-17 02:57

I\'m using the %% operator on PostgreSQL\'s hstore type which converts a hstore (key-value type effectively) into an array whose elements alternate {{key, value

3条回答
  •  青春惊慌失措
    2020-12-17 03:45

    From a curiosity standpoint, does anyone know why these are not supported?

    One generic answer is because arrays are intrinsically anti-relational. Removing repeating values is how you achieve 1st normal form. To have repeating groups of repeating groups seems quite insane from a relational theoretical standpoint.

    In general, the relationally-correct thing to do is to extract a table for your repeating values. So if you modeled something like this:

    CREATE TABLE users (
      id integer primary key,
      name varchar,
      favorite_colors varchar[],
      ...
    );
    

    it would behoove you to redefine this relationally like so:

    CREATE TABLE users (
      id integer primary key,
      name varchar,
      ...
    );
    
    CREATE TABLE favorite_colors (
      user_id integer references users,
      color varchar
    );
    

    Or even:

    CREATE TABLE users (
      id integer primary key,
      name varchar,
      ...
    );
    
    CREATE TABLE colors (
      color varchar primary key
    );
    
    CREATE TABLE favorite_colors (
      user_id integer references users,
      color varchar references colors,
      primary key (user_id, color)
    );
    

    Hstore supports a lot of functions, many of which would make it easy to integrate it into a relational worldview. I think the simplest way to solve your problem would be to use the each function to convert your hstore values into relations you can then use like a normal set of values. This is how you address having multiple values in other databases anyway: querying, and working with result sets.

提交回复
热议问题