使用逗号分隔值连接列上的表

时间:2016-11-23 07:31:38

标签: sql postgresql

表1:mas_book_author

author_id   |    author_name     
------------+----------------
 1          | jhon
 2          | roobini
 3          | virat
 4          | sachin
 5          | siva
 6          | priya

表4:mas_bk_accession_entry

id(int)(pk)  | author_ids(varchar)
-------------+-------------------
1            | 1,5
2            | 5,1
3            | 2,5
4            | 3,5
5            | 4,5  

我的结果应该是这样的:

author_name |count
------------+------
 jhon,siva  | 2    

这是我的SQL查询

select b.author_name,COUNT(*) as totbook 
from mas_bk_accession_entry a
   join mas_book_author as b 
     on b.author_id in (select cast((unnest(string_to_array(f.author_ids,',')) ) as int) as author_ids 
                        from mas_bk_accession_entry f)
where a.author_ids = '1,5'
group by b.author_name

1 个答案:

答案 0 :(得分:1)

您可以简化连接条件,并且需要string_agg()来获取以逗号分隔的作者姓名列表:

select string_agg(author_name,','), count(*)
from mas_book_author b
  join mas_bk_accession_entry e on b.author_id = any(string_to_array(author_ids,',')::int[])
where e.author_ids = '1,5';

在线示例:http://rextester.com/NVNBH72654

但你应该真正修复你的数据模型。存储逗号分隔值(如author_ids列)是一个非常非常糟糕的选择。