SQL 查询:通过获取具有最大 ID 编号的条目来过滤重复条目,然后将另一个 table 的数据与之连接
SQL Query: Filter duplicate entries by getting the entries with the maximum id number then join another table's data with it
我正在尝试从表 1 中获取所有 ID、std_name,以及从表 2 中获取所有 ID、分数,其中表 2 的 std_id 与表 1 的 ID 匹配,并且 deleted_at 应该为空对于 table1 和 table2 的所有条目。但是table2可以有重复的std_ids,在那种情况下,我只想要table2中具有最大id号的条目。
示例表 1:
id
std_name
deleted_at
1
jhon
null
2
sam
null
3
joe
null
示例表 2:
id
std_id
score
deleted_at
1
1
10
null
2
2
20
null
3
1
30
null
到目前为止,我已尝试使用此查询:
const query = knex.select([
't1.id as t1id',
't1.std_name as name',
't2.score as score'
])
.from('table1 as t1')
.leftJoin('table2 as t2', function () {
this.on('t2.std_id', '=', 't1.id')
})
.joinRaw('left join (select MAX(id) as id, std_id from table2 group by std_id) as kst on kst.std_id = t2.std_id');
query.where({'t1.deleted_at': null}).orderBy('t1.id')
为上述查询生成的结果:
id
name
score
1
jhon
30
2
sam
20
但这只是returns来自table2的重复条目的最大id条目并省略了table1的条目,但我还想要来自table1的id不包含在std_id中表 2.
我想要的输出:
id
name
score
1
jhon
30
2
sam
20
3
joe
null
您可以使用 window 函数。在 SQL 中看起来像:
select t1.*, t2.score
from table1 t1 left join
(select t2.*,
row_number() over (partition by t2.std_id order by t2.id desc) as seqnum
from table2 t2
) t2
on t2.std_id = t1.id and t2.seqnum = 1;
我正在尝试从表 1 中获取所有 ID、std_name,以及从表 2 中获取所有 ID、分数,其中表 2 的 std_id 与表 1 的 ID 匹配,并且 deleted_at 应该为空对于 table1 和 table2 的所有条目。但是table2可以有重复的std_ids,在那种情况下,我只想要table2中具有最大id号的条目。
示例表 1:
id | std_name | deleted_at |
---|---|---|
1 | jhon | null |
2 | sam | null |
3 | joe | null |
示例表 2:
id | std_id | score | deleted_at |
---|---|---|---|
1 | 1 | 10 | null |
2 | 2 | 20 | null |
3 | 1 | 30 | null |
到目前为止,我已尝试使用此查询:
const query = knex.select([
't1.id as t1id',
't1.std_name as name',
't2.score as score'
])
.from('table1 as t1')
.leftJoin('table2 as t2', function () {
this.on('t2.std_id', '=', 't1.id')
})
.joinRaw('left join (select MAX(id) as id, std_id from table2 group by std_id) as kst on kst.std_id = t2.std_id');
query.where({'t1.deleted_at': null}).orderBy('t1.id')
为上述查询生成的结果:
id | name | score |
---|---|---|
1 | jhon | 30 |
2 | sam | 20 |
但这只是returns来自table2的重复条目的最大id条目并省略了table1的条目,但我还想要来自table1的id不包含在std_id中表 2.
我想要的输出:
id | name | score |
---|---|---|
1 | jhon | 30 |
2 | sam | 20 |
3 | joe | null |
您可以使用 window 函数。在 SQL 中看起来像:
select t1.*, t2.score
from table1 t1 left join
(select t2.*,
row_number() over (partition by t2.std_id order by t2.id desc) as seqnum
from table2 t2
) t2
on t2.std_id = t1.id and t2.seqnum = 1;