首页 > 解决方案 > SQL 查询:仅当登录的用户 ID 在现有表中不存在时才将一个表与现有的多个连接表连接起来并获取它的条目

问题描述

我当前没有加入 table3 的代码从 table1 获取所有 id、name、employee_id,以及从 table2 获取所有 id、kpi_id、score,其中 table2 的 kpi_id 与 table1 的 id 匹配,并且对于 table1 和 table2 的所有条目,deleted_at 为空。但是 table2 可以有重复的 kpi_ids,在这种情况下,我只能从 table2 中获取具有最大 id 号的条目。

现在,除了上述结果之外,我想要获取 table1 的每个 id 的所有条目,如果employee_id 与 this._loggedInUser.id 匹配,并且如果 this._loggedInUser.id 与 table1 中的任何employee_id 都不匹配,那么查看 this._loggedInUser.id 是否与 table3 中的contributor_id 匹配,如果匹配则从 table1 和 table3 中获取相应 kpi_id 的所有 KPI 信息。

样品表1:

ID 姓名 员工ID 删除_at
1 kpi1 5 无效的
2 kpi2 5 无效的
3 kpi3 9 无效的

样品表2:

ID kpi_id 分数 删除_at
1 1 10 无效的
2 2 20 无效的
3 1 30 无效的

样品表3:

ID kpi_id 贡献者ID 删除_at
1 1 7 无效的
2 1 9 无效的

到目前为止,我已经尝试了以下查询:

const query = knex.select([
            't1.id as id',
            't1.name as name',
            't1.employee_id as employeeId',
            't2.kpi_id as kpiId',
            't2.score as userInputScore',
            't2.id as kpiScoreId',
            't3.contributor_id as contributorId'
        ]).from('table1 as t1')
            .joinRaw('left join (select t2.*, row_number() ' +
                'over (partition by t2.kpi_id order by t2.id desc) as seqnum from table2 t2) t2 ' +
                'on t2.kpi_id = k.id and t2.seqnum = 1'
            ).joinRaw('left join (select t3.*, row_number() ' +
                'over (partition by t3.kpi_id order by t3.id desc) as seqnum from contributors t3) t3 ' +
                'on t3.kpi_id = t1.id and t3.seqnum = 1'
            )

            const searchClause = {
            condition1: {
                't1.deleted_at': null,
                't3.deleted_at': null,
                't1.employee_id': this._loggedInUser.id,
            },
            condition2: {
                't1.deleted_at': null,
                't3.deleted_at': null,
                't3.contributor_id': this._loggedInUser.id,
            },
        }

            if (searchClause.condition1) {
            query.where(searchClause.condition1).orderBy('k.id')
        } else if (searchClause.condition2) {
            query.where(searchClause.condition2).orderBy('k.id')
        }

       return await query.then(kpi => kpi);
    }

现在,如果我以用户 7 即 this._loggedInUser.id = 7 登录,即使 7 是 table3 中 kpi_id = 1 的contributor_id,也不会生成任何结果。上述查询仅在 this._loggedInUser.id 与 table1 的employee_id 匹配时才有效如果它在 table1 中不匹配,则转到 table3,如果特定 kpi_id 有多个贡献者,它只会从 table3 中获取具有最大 id 的那个,在这种情况下属于 contributor_id = 9,它不匹配 this._loggedInUser.id = 7 所以它不返回任何结果。

因此,如果我以用户 ID = 7 的身份登录,我想要的输出应该如下所示:

t1.id t2.id kpi_id 分数 员工ID 贡献者ID
1 3 1 30 5 7

标签: sqlknex.js

解决方案


推荐阅读