【问题标题】:SQL query to retrieve entries if userId matches table1's employee_id or table2's contributor_id如果 userId 与 table1 的employee_id 或 table2 的contributor_id 匹配,则 SQL 查询检索条目
【发布时间】:2021-05-03 12:31:10
【问题描述】:

如果提供的 userId 与 table1 中的 employee_id 或 table2 中的contributor_id 匹配,我正在尝试从 table1 和 table2 中检索所有 kpi_id、kpi_name、employee_id、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 的贡献者,这将返回重复的条目。我当前的 SQL 查询会生成这个:

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

【问题讨论】:

    标签: sql knex.js


    【解决方案1】:

    添加 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');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 2020-10-30
      • 2015-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多