我想在 typeorm 中合并两个表。
第一个版本: 我为每个表创建了 sql 原始查询
const tableUn = this.tableUnion.createQueryBuilder('tu')
.select('id')
.addSelect('description', 'name')
.getQuery();
const tableTg = this.tags.createQueryBuilder('tg')
.select(['id', 'name'])
.getQuery();
使用联合创建 slq 原始查询后:
const tags = await entityManager.query(`${ tableUn } UNION ${ tableTg }`);
创建新实体并将收到的数据插入其中。
const createdEntity = entityManager.create(TableUnion, tags);
最后,我想在连接查询生成器中使用这个实体,但它不起作用
const result = await connection.createQueryBuilder()
.from(createdEntity, 'cE')
.getRawMany();
第二个版本:
const a = connection
.createQueryBuilder()
.select('*')
.from(qb => qb
.from(TableUnion, 'tu')
.select('id')
.addSelect('description', 'tu.name'),
'ttu'
)
.addFrom(qb => qb
.from(TagsEntity, 'tg')
.select('id')
.addSelect('tg.name'),
'ttg'
)
它用两个表中的数据和列创建了表,但没有连接
最佳答案
我为自己找到了这个解决方案。
// two queries with different parameters from the same table
const query1WithParams = repo.createQueryBuilder("table1")
.select("table1.id")
.where("table1.id = :input_id" , { input_id : 5 })
.getQueryAndParameters();
const query2WithParams = repo.createQueryBuilder("table1")
.select("table1.id")
.where("table1.id = :input_id" , { input_id : 10 })
.getQueryAndParameters();
请记住,如果您没有任何参数,最好使用 .getQuery()
而不是 .getQueryAndParameters()
。
所以让我解释一个你可能会遇到的问题。
如果你没有参数,一切都很好,你可以在没有任何准备的情况下使用你的查询。但是如果你有像我在顶部的例子那样的参数,你必须自己更改参数占位符以避免它们发生冲突。
如果您查看这两个的结果查询,您会发现它们都有确切的 WHERE
子句
-- Result of query1WithParams and the parameter must be 5
WHERE "table1"."id" > $1
-- Result of query2WithParams and the parameter must be 10
WHERE "table1"."id" > $1
如您所见,我们有两个值 (5
) 的占位符,但它不起作用,因此我们必须将其中一个更改为 $2
(不同的数据库有自己的参数格式,这个例子是关于 Postgres
的。如果你想了解更多,请查看 this question。)
您可以像这样更改其中之一:
const [query2, params2] = query2WithParams
const correct_query2 = query.replace("$1", "$2")
然后,你必须将参数数组合并为一个(它们的顺序很重要)
const [query1, params1] = query1WithParams
const correct_params = [...params1, ...params2]
现在您可以将它们用作联合的输入查询了。
const result = await repo.manager.query(
"(" + query1 +")" + "UNION" + "(" + correct_query2 +")",
correct_params
)
https://stackoverflow.com/questions/68317806/
相关文章:
javascript - 来自 "pages/[...slug].js"的 Next.js 路由不起
c++ - std::reference_wrapper
android - 如何公开 StateFlow 但启动和停止底层 Flow
javascript - 在开始下一个功能之前等待一个功能完成
postgresql - psql:致命:用户 ""aws rds Postgresql 的 PAM
android-studio - 在 Play Store Console 中更改草稿应用程序的应用