You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写SQL查询按条件筛选值,获取article对应的有效component记录

SQL查询解决方案

前提假设

这里假设你的表名为 article_component,对应的三个字段名分别为:

  • article:存储article编号
  • component:存储对应组件编号
  • change_number:存储变更号

方案1:使用ROW_NUMBER窗口函数(推荐,入门易理解)

SELECT article, component, change_number
FROM (
    SELECT 
        *,
        -- 按article分组,同个article下的记录按change_number倒序排序
        ROW_NUMBER() OVER (PARTITION BY article ORDER BY change_number DESC) AS rn
    FROM article_component
) t
WHERE rn = 1;

逻辑说明

同一个article的所有记录排序时,有值的change_number会排在NULL前面,取排序第1位的记录就刚好满足需求:

  • 如果article有带变更号的记录,就取变更号对应的新组件记录
  • 如果article只有无变更号的记录,就取这条NULL的记录

方案2:关联查询(兼容不支持窗口函数的旧版数据库)

SELECT a.*
FROM article_component a
LEFT JOIN article_component b 
    ON a.article = b.article 
    AND b.change_number IS NOT NULL
WHERE 
    -- 要么这个article没有带变更号的记录,直接取本身
    b.article IS NULL 
    -- 要么当前记录就是这个article带变更号的记录
    OR a.change_number IS NOT NULL;

结果验证

针对你给出的示例数据,以上两种查询返回的结果完全符合预期:

articlecomponentchange_number
0001187301040994000000000001
0001187501020151NULL
0001188101025465NULL
0001188301045066NULL

内容的提问来源于stack exchange,提问作者Botond Bálint

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 10:36:00