0

我有一个如下所示的表格

表名 - 属性

|runId|listingId|listingName
   1 123 美国广播公司
   1 234 分辨率
   2 123 abcd
   2 567 吉
   2 234 定义

正如您在上面的代码中看到的,有一个 runId 和一个列表 Id。我正在尝试获取特定的 runId ,它们是添加的新列表(在这种情况下,runId 2 是它的第 4 行,列表 id 为 567 ),哪些是更新的列表 ID(在这种情况下,它的第 3 行和第 5 行清单 ID 分别为 123 和 234)

我正在尝试自我加入,它在新更新中正常工作,但新添加给我带来了麻烦

从属性 p1 中选择 p1.*
    INNER JOIN 属性 p2
        ON p1.listingid = p2.listingid
            其中 p1.runid=456 和 p2.runid!=456

上面的查询为我提供了表中正确的更新记录。但我无法找到新的列表。我使用 p1.listingid != p2.listingId ,左外连接,仍然无法工作。

4

3 回答 3

0

你可以试试这个。

with cte as (
select row_number() over (partition by listingId order by runId) as Slno, * from property 
)
select * from property where listingId not in (
select  listingId from cte as c where slno>1 
)    --- for new listing added

with cte as (
select row_number() over (partition by listingId order by runId) as Slno, * from property 
)
select * from property where listingId in (
select  listingId from cte as c where slno>1 
)   --- for modified listing 


于 2019-09-05T09:26:16.263 回答
0

我会使用ROW_NUMBER()它的分析功能。

SELECT
    T.*
FROM
    (
        SELECT
            T.*,
            CASE
                WHEN ROW_NUMBER() OVER(
                    PARTITION BY LISTINGID
                    ORDER BY
                        RUNID
                ) = 1 THEN 'INSERTED'
                ELSE 'UPDATED'
            END AS OPERATION_
        FROM
            PROPERTY
    )
WHERE
    RUNID = 2
    -- AND OPERATION_ = 'INSERTED'
    -- AND OPERATION_ = 'UPDATED'

listingid如果在前面的任何一个中添加,这将提供更新后的结果runid

干杯!!

于 2019-09-05T09:41:07.597 回答
0

为此,我会推荐existsnot exists。对于更新:

select p.*
from property p
where exists (select 1
              from property p2
              where p2.listingid = p.listingid and
                    p2.runid < p.runid
             );

如果您想要特定的结果runid,请添加and runid = ?到外部查询。

对于新列表:

select p.*
from property p
where not exists (select 1
                  from property p2
                  where p2.listingid = p.listingid and
                        p2.runid < p.runid
                 );

使用 上的索引property(listingid, runid),我希望这比使用窗口函数的解决方案具有更好的性能。

是一个 db<>fiddle。

于 2019-09-05T11:20:20.357 回答