【问题标题】:Postgresql Select rows where column::text = array::text[]Postgresql 选择 column::text = array::text[] 的行
【发布时间】:2023-02-13 21:44:26
【问题描述】:

这类似于Postgresql Select rows where column = array问题

create table students (id int, name text);
insert into students values 
(1,'AA'),
(2,'BB'),
(3,'CC'),
(4,'DD');

create table classes (name text,students text[]);
insert into classes values
('CL-1','{2,4}'),
('YL-2','{2,1,4}'),
('CL-3','{2,3}'),
('BL-33','{2}'),
('CL-5','{1,3,4}'),
('CL-6','{4}');

我怎样才能得到每个班级的学生姓名?

select cl.name, 
       (select st.names 
        from student st 
        where st.id in cl.student) as student_names -- exp: AA,BB,CC
from class cl;

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    您可以加入表并重新聚合与数组中的 ID 对应的名称:

    select c.name as class_name,
           string_agg(s.name,',') as student_names
    from classes c
            inner join students s
            on s.id::text=any(students)
    group by c.name;
    -- class_name | student_names
    --------------+---------------
    -- CL-5       | AA,CC,DD
    -- YL-2       | AA,BB,DD
    -- CL-6       | DD
    -- BL-33      | BB
    -- CL-1       | BB,DD
    -- CL-3       | BB,CC
    

    online demo

    【讨论】:

      猜你喜欢
      • 2023-02-21
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 2014-12-06
      • 1970-01-01
      相关资源
      最近更新 更多