在postgresql中实现关系代数除法运算符

时间:2013-11-08 16:39:38

标签: postgresql relational-database relational-division

在postgresql中使用语法支持排序实现关系代数除法运算符可以指导吗? 编辑:这是为了处理postgresql的源代码。我需要在Postgresql中添加除法功能。

1 个答案:

答案 0 :(得分:1)

不确定您对排序语法支持意味着什么,但关系除法运算符似乎只是一个错综复杂的联接:

select a_.id
from (select a.id, array_agg(a.b_id) as b_ids from a group by a.id) as a_
join (select array_agg(b.id) as b_ids from b) as b_ on b_.b_ids <@ a_.b_ids

http://en.wikipedia.org/wiki/Relational_algebra#Division_.28.C3.B7.29


denis=# create table a (id int, b_id int);
CREATE TABLE
denis=# create table b (id int);
CREATE TABLE
denis=# insert into a values (1,1), (1,2), (1,3), (2,1), (2,3), (3,1), (3,2);
INSERT 0 7
denis=# insert into b values (1), (2);

denis=# select a_.id from (select a.id, array_agg(a.b_id) as b_ids from a group by a.id) as a_ join (select array_agg(b.id) as b_ids from b) as b_ on b_.b_ids <@ a_.b_ids;
 id 
----
  1
  3
(2 rows)