【问题标题】:I am using Left join with other table . There are multiple rows with the same p_id on other table . I want the row with latest p_id [duplicate]我正在使用 Left join 与其他表。其他表上有多个具有相同 p_id 的行。我想要最新 p_id 的行 [重复]
【发布时间】:2022-11-29 10:06:05
【问题描述】:

我正在使用 Left join( on A.a_id = B.b_id ) 来连接表 A 和 B 。另一个表上有多个具有相同 p_id 的行。 我想要最新 p_id 的行。

连接表 A 和表 B 的列是 a_id 和 p_id。我想加入 表和组的记录,只想要表 B 记录与 max bid 。 谁能帮我用 mysql 查询找到所需的结果。我已经发布了 期望的结果如下。

Mysql查询:

 Select * from A Left JOIN B ON A.a_id =B.p_id group by p_id 
 having max(b_id)

表A

a_id  column1 
 1   Adam
 2   Voge

表B

b_id  p_id   column2
 1   1    dash
 2   1    Hash
 3   2    kyu

期望的结果应该是这样的

a_id b_id   column1 column2
 1   2      Adam    Hash 
 2   3      Voge    kyu

【问题讨论】:

  • 请编辑问题并显示您目前的查询。
  • @RohitGupta 更新了它

标签: php mysql sql greatest-n-per-group


【解决方案1】:

@surya辛格..

with joined_data as (
select 
a.a_id,a.column1,b.p_id,b.column2
from tablea a
inner join tableb b on a.a_id= b.b_id
),
find_recent_data as (
select 
a_id,column1,
column2,
row_number() over (partition by a_id order by p_id desc)  key_column
from joined_data)
select * from find_recent_data 
where key_column=1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 2011-07-25
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多