【问题标题】:Arrays of custom type in PostgreSQLPostgreSQL 中自定义类型的数组
【发布时间】:2017-04-13 21:27:40
【问题描述】:

我在 Postgres 中有一个自定义类型:

CREATE TYPE child AS
   (id integer,
    name text,
    surname text,
    age integer);

和表

CREATE TABLE parent
(
  id integer NOT NULL,
  name text NOT NULL,
  surname text NOT NULL,
  age integer NOT NULL,
  childs child[],
  CONSTRAINT parent_pkey PRIMARY KEY (id)
)

我希望父母有一个名字为“约翰”的孩子

我尝试过类似的方法:

select id, name
  from parent
where 'John' = any  (select (unnest(childs)).name from parent)

但我接待了所有的父母。 如果有人解决了我的问题,我将不胜感激。

【问题讨论】:

    标签: arrays database postgresql


    【解决方案1】:

    这对谁有帮助?..

    with un as (
    select (unnest(childs)).name, id from parent
    ) 
    select 
      id
    , name 
    from parent 
    join un on un.id = parent.id 
    where un.name = 'John'
    ;
    

    【讨论】:

    • 我必须添加第二个选择 parent.id 和 parent.name 而不是 id 和 name,然后它就可以工作了,谢谢
    【解决方案2】:

    您必须以某种方式关联第一个父级和第二个父级。您可以使用 Vao Tsun 的查询,也可以尝试使用相关查询:

    select id, name
      from parent as p1
    where 'John' = any  (select (unnest(childs)).name from parent as p2 where p1.id = p2.id)
    

    【讨论】:

      【解决方案3】:

      如果给表加上别名,则更容易发现问题:

      SELECT p1.id, p1.name
      FROM parent p1
      WHERE 'John' = ANY (SELECT (UNNEST(p2.childs)).name FROM parent p2)
      

      WHERE 子句甚至没有提到p1;它正在查看parent 表的独立副本。但是根本不需要引入第二个表格副本:

      SELECT id, name
      FROM parent
      WHERE 'John' = ANY (SELECT (UNNEST(childs)).name)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-05
        • 2011-01-03
        • 2012-12-23
        • 1970-01-01
        • 2012-03-20
        • 2022-01-06
        • 1970-01-01
        • 2011-10-15
        相关资源
        最近更新 更多