sql - 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)
类似于一对多但在所有关系之间具有逻辑运算符的东西。有没有直接的方法可以做到这一点?
提前致谢,
朱利安
- 更新:正如@Rezu 所要求的 - 为了能够编写一个返回文本的查询,例如:
First Test 1 := Second Test 1 AND Second Test 2
零件AND
可以是AND
,OR
等NOT
希望这能澄清我想要实现的目标
- 更新 1: 这几乎是我想要实现的目标。结果查询是这样的:
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
希望能解释我的目标是什么
解决方案
基本上这是我的解决方案。也许有更好的,但这就是我想出的
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
推荐阅读
- python-3.x - Flask:render_template 将数据帧处理为 html
- c# - 我的代码真的是异步执行的吗?
- python - 使用 Python 3.7.0 安装 Tensorflow 时出错 - 为什么 pip3 不能自行解决依赖关系?
- bash - 在 xxd 之后找不到 Bash 命令
- bash - 在 Bash 中使用 if 语句比较两个整数时遇到问题
- azure - Flask 应用程序绝对 url 在 azure 应用程序服务中以 http 而不是 https 重定向
- asp.net - ASP.NET 问题 - Nuget 包丢失
- reactjs - 为什么博客不显示为列表?
- r - 我应该在 R 中运行哪种测试来将一个因子与一个数字进行比较,然后再将因子与因子进行比较?
- sql - 插入 ... 从表中选择列 .... 加入 #temptable