首页 > 解决方案 > PostgreSQL 两个表与表达式关系

问题描述

我需要用它们之间的二进制表达式来处理两个表之间的关系。我会尽力澄清。有两张桌子

--First
id | Name
1  | First Test 1
2  | First Test 2

--Second
id | Name
1  | Second Test 1
2  | Second Test 2 

我希望能够使用如下伪代码的逻辑表达式链接这两个表:

First(id=1) => Second(id=1) && (AND) Second(id=2)

类似于一对多但在所有关系之间具有逻辑运算符的东西。有没有直接的方法可以做到这一点?

提前致谢,

朱利安

First Test 1 := Second Test 1 AND Second Test 2

零件AND可以是AND,ORNOT

希望这能澄清我想要实现的目标

First Test 1 := Second Test 1
First Test 1 := Second Test 2
First Test 2 := Second Test 3

我想要实现的是:

First Test 1 := Second Test 1 AND First Test 1 := Second Test 2
First Test 2 := Second Test 3

希望能解释我的目标是什么

标签: sqlpostgresql

解决方案


基本上是我的解决方案。也许有更好的,但这就是我想出的

create table first (
    id serial primary key,
    name text
);

insert into first (name) values (
'First Test 1'),('First Test 2');

create table second (
    id serial primary key,
    name text
);

insert into second (name) values (
'Second Test 1'),('Second Test 2'),('Second Test 3');

create table first_second (
    first_id bigint,
    second_id bigint,
    logical_operator text
);

insert into first_second (first_id, second_id,logical_operator) values (
1,1,''),(1,2,'AND'),(2,3,'');

查询是:

SELECT first.name || ' := ' || 
string_agg(first_second.logical_operator || ' ' || second.name, ' ') 
as name
FROM 
  first
 JOIN first_second ON first_second.first_id = first.id
 JOIN second ON first_second.second_id = second.id
 Group by first.name

推荐阅读