SQL 如果 userId 与表 1 的 employee_id 或表 2 的 contributor_id 匹配,则查询检索条目

SQL query to retrieve entries if userId matches table1's employee_id or table2's contributor_id

我正在尝试从 table1 和 table2 中检索所有 kpi_id、kpi_name、employee_id、contributor_id,如果提供的 userId 与 employee_id 来自表 1 或表 2 中的 contributor_id。

示例表 1:

id kpi_name employee_id
1 kpi1 5
2 kpi2 6
3 kpi3 9

示例表 2:

id kpi_id contributor_id
1 1 9
1 3 5
1 1 6

现在,如果给定的 userId 为 5,那么由于该用户是 kpi_id 1 的所有者和 kpi_id 3 的贡献者,结果应如下所示:

我想要的输出:

kpi_id kpi_name employee_id contributor_id
1 kpi1 5 5
3 kpi3 9 5

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

const query = knex.select([
            't1.id as kpiId',
            't1.name as kpiName',
            't1.employee_id as employeeId',
            't2.contributor_id as contributorId'
        ]).from('table1 as t1')
            .leftJoin('table2 as t2', function () {
                this.on('t2.kpi_id', '=', 't1.id')
            })

           query.where({
                't1.employee_id': this._loggedInUser.id,
            }).orWhere(
                't2.contributor_id': this._loggedInUser.id,).orderBy('t1.id');

但是,如果同一 kpi_id 有多个贡献者,则此 returns 重复条目。我当前的 SQL 查询生成了这个:

kpi_id kpi_name employee_id contributor_id
1 kpi1 5 5
1 kpi1 5 6
3 kpi3 9 5

添加 distinct 和 groupBy 解决了我的问题:

const query = knex.select([
            't1.id as kpiId',
            't1.name as kpiName',
            't1.employee_id as employeeId',
            't2.contributor_id as contributorId'
        ]).from('table1 as t1')
            .leftJoin('table2 as t2', function () {
                this.on('t2.kpi_id', '=', 't1.id')
            }).groupBy('t1.id', 't1.name', 't1.employee_id', 't2.contributor_id')

           query.where({
                't1.employee_id': this._loggedInUser.id,
            }).orWhere(
                't2.contributor_id': this._loggedInUser.id,).orderBy('t1.id').distinctOn('t1.id');