python - JSON对象列上的PostgreSQL JOIN
问题描述
我应该在 postgres 上加入 3 个不同的表:
- lote_item(我有一些书籍 ID)
- lote_item_log(我有一个列“属性”,带有一个 JSON 对象,例如{“aluno_id”:“2823”,“aluno_email”:“someemail@outlook.com”,“aluno_unidade”:174,“livro_codigo”:“ XOZK-0NOYP0Z1EMJ"} ) - Obs.: aluno_unidade上的一些值是空的
最后
- 公司(我有每个 aluno_unidade 的每个学校名称。例如:aluno_unidade = 174 ==> nome_fantasia = mySchoolName)。
加入前两个表很容易,因为lote_item_log有一个外键,我可以这样匹配:
SELECT * FROM lote_item 加入 lote_item_log on lote_item.id = lote_item_log.lote_item_id
现在,我需要获取包含在表company中的School Name以及表lote_item_log中的aluno_unidade ID 。
我目前的查询是:
SELECT
*
FROM
lote_item
JOIN
lote_item_log
ON
lote_item.id = lote_item_log.lote_item_id
JOIN
company
ON
(
SELECT
JSON_EXTRACT_PATH_TEXT(attributes, 'aluno_unidade')::int
FROM
lote_item_log
WHERE
operation_id = 6
) = company.senior_id
WHERE
item_id = {book_id};
operation_id确定哪个学校是活跃的。
我得到的错误:
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.CardinalityViolation) 多于一行由用作表达式的子查询返回
我尝试了 LIMIT 1,但后来我得到了一个空数组。
我需要的是:
lote_item.created_at | lote_item.updated_at | lote_item.item_id | uuid | aluno_email | c014_id | nome_fantasia | cnpj | is_franchise | is_active
somedate | somedate | some_item_id | XJW4 | someemail@a | some_id | SCHOOL NAME | cnpj | t | t
解决方案
我知道了。
不确定这是最好的方法,但工作......
SELECT
*
FROM
lote_item
JOIN
lote_item_log
ON
lote_item.id = lote_item_log.lote_item_id
JOIN
company
ON
JSON_EXTRACT_PATH_TEXT(attributes, 'aluno_unidade')::int = company.senior_id
WHERE
item_id = {book_id};
推荐阅读
- java - Java将具有原始浮点字段的对象序列化为Json
- maven - 当我在 pom 上执行 maven add project 时,IntelliJ 不必要地将文件添加到 git
- r - 如何使用 cbind 从列表中添加索引?
- javascript - 如何从rest API url下载pdf
- php - Laravel 在侧代理网络中发送邮件
- jquery - 如何使用 AngularJS 显示完整的日历动态事件?
- mysql - mySQL - 如何将“压缩为 1 列数据”转换为具有多列的标准表
- html - 透明的粘性导航栏不起作用
- python - 如何使用来自不同 CSV 文件的多列循环执行回归
- java - 如何使用 Spring Boot 编写集成/系统测试以使用存储库测试服务