在 Knex.js 中派生别名 table
Aliasing derived table in Knex.js
我正在使用 Knex,我想将此原始查询转换为 Knex 语法:
SELECT
t.id,
t.objectId,
t.objectType
FROM (
SELECT
tableA.tableC_Id AS Id,
tableA.id AS objectId,
'TypeA' AS objectType
FROM tableA
UNION
SELECT
tableB.tableC_Id AS Id,
tableB.id AS objectId,
'TypeB' AS objectType
FROM tableB
) t
INNER JOIN tableC ON tableC.id = t.Id
我没有内部连接的尝试:
const qb = di
.get(DatabaseConnection)
.queryBuilder()
.select('*')
.from(() => {
tableA
.queryBuilder()
.select([
{ id: tableA.col('Id') },
{ objectId: tableA.col('id') },
{ objectType: connection.raw('\'TypeA\'') },
])
.union([
tableB
.queryBuilder()
.select([
{ id: tableB.col('Id') },
{ objectId: tableB.col('id') },
{ objectType: tableB.raw('\'TypeB\'') },
])
])
.as('t');
});
但是 Knex 将其转换为
SELECT * FROM (SELECT * )
。我不喜欢使用原始 SQL-查询,这可能吗?
knex(
knex('tableA').select(
'tableA.tableC_Id as Id',
'tableA.id as objectId',
knex.raw("? as objectType", ['TypeA'])
)
.union([
knex('tableB').select(
'tableB.tableC_Id as Id',
'tableB.id as objectId',
knex.raw("? as objectType", ['TypeB'])
)
])
.as('t')
)
.select('t.id', 't.objectId', 't.objectType')
.join('tableC', 'tableC.id', 't.Id')
输出:
select "t"."id", "t"."objectId", "t"."objectType"
from (
select "tableA"."tableC_Id" as "Id", "tableA"."id" as "objectId", ? as objectType
from "tableA"
union select "tableB"."tableC_Id" as "Id", "tableB"."id" as "objectId", ? as objectType
from "tableB"
) as "t" inner join "tableC" on "tableC"."id" = "t"."Id"
我正在使用 Knex,我想将此原始查询转换为 Knex 语法:
SELECT
t.id,
t.objectId,
t.objectType
FROM (
SELECT
tableA.tableC_Id AS Id,
tableA.id AS objectId,
'TypeA' AS objectType
FROM tableA
UNION
SELECT
tableB.tableC_Id AS Id,
tableB.id AS objectId,
'TypeB' AS objectType
FROM tableB
) t
INNER JOIN tableC ON tableC.id = t.Id
我没有内部连接的尝试:
const qb = di
.get(DatabaseConnection)
.queryBuilder()
.select('*')
.from(() => {
tableA
.queryBuilder()
.select([
{ id: tableA.col('Id') },
{ objectId: tableA.col('id') },
{ objectType: connection.raw('\'TypeA\'') },
])
.union([
tableB
.queryBuilder()
.select([
{ id: tableB.col('Id') },
{ objectId: tableB.col('id') },
{ objectType: tableB.raw('\'TypeB\'') },
])
])
.as('t');
});
但是 Knex 将其转换为
SELECT * FROM (SELECT * )
。我不喜欢使用原始 SQL-查询,这可能吗?
knex(
knex('tableA').select(
'tableA.tableC_Id as Id',
'tableA.id as objectId',
knex.raw("? as objectType", ['TypeA'])
)
.union([
knex('tableB').select(
'tableB.tableC_Id as Id',
'tableB.id as objectId',
knex.raw("? as objectType", ['TypeB'])
)
])
.as('t')
)
.select('t.id', 't.objectId', 't.objectType')
.join('tableC', 'tableC.id', 't.Id')
输出:
select "t"."id", "t"."objectId", "t"."objectType"
from (
select "tableA"."tableC_Id" as "Id", "tableA"."id" as "objectId", ? as objectType
from "tableA"
union select "tableB"."tableC_Id" as "Id", "tableB"."id" as "objectId", ? as objectType
from "tableB"
) as "t" inner join "tableC" on "tableC"."id" = "t"."Id"