nyse
V2EX  ›  数据库

SQL: 一对多的关系,如何获取其中一条作为一个字段的值?

  •  
  •   nyse · Oct 11, 2019 · 3413 views
    This topic created in 2431 days ago, the information mentioned may be changed or developed.

    假设

    A 表字段:id, name, update_time

    B 表字段:id, aid, content, update_time

    其中,B 表的 aid 对应 A 表的 id,且会有多条 aid 相同,即 A 表的一条数据对应 B 表多条数据。

    在查询 A 表的时候 select * from A ,同时要关联读取 B 表中一条对应 aid 的 content 字段,这一条数据可能是根据更新时间倒序的最后一条。

    总之,最后想要的查询结果含有 A.* B.content

    这种需求怎么实现比较合理?

    11 replies    2019-10-12 07:04:34 +08:00
    eason1874
        1
    eason1874  
       Oct 11, 2019
    直接参考 WordPress 分类关系表设计
    aragakiyuii
        2
    aragakiyuii  
       Oct 11, 2019 via Android
    select a.*, b.content from A a, (select aid, content, row_number() over (order by update_time desc partition by aid ) as rn from B where rn = 1) b where a.id = b.aid

    oracle 没测试过,如果想要 A 表全部记录得左连接
    ipiao
        3
    ipiao  
       Oct 11, 2019
    建议写 2 条 sql,拒绝 join
    Doldrums
        4
    Doldrums  
       Oct 11, 2019
    对 B 表 ROW_NUMBER() over(partition...)排序之后 leftjoin 限制 B.rowNum=1
    bumz
        5
    bumz  
       Oct 11, 2019 via iPhone
    select a.*, b.content from a, b where a.id = b.aid limit 1;

    没测
    想时间倒序就加 order by
    bumz
        6
    bumz  
       Oct 11, 2019 via iPhone
    @bumz 看错,忽略
    QiuSe
        7
    QiuSe  
       Oct 11, 2019
    SELECT a.id,a.`name`,a.update_time, ( SELECT b.content FROM b GROUP BY b.aid HAVING MAX(b.update_time) and b.aid =1) as bcontent
    FROM a
    INNER JOIN b
    WHERE b.aid = a.id = 1
    不知道对不对?
    Caballarii
        8
    Caballarii  
       Oct 11, 2019
    建议分开写 sql,多不了几条,A 表多了就分页查
    wangyzj
        9
    wangyzj  
       Oct 11, 2019
    content 不应该是属于 a 表才对么
    nyse
        10
    nyse  
    OP
       Oct 11, 2019
    @wangyzj #9 不是,A 表一个条目对应 B 表多条,但只要选取 B 表其中一条
    zjsxwc
        11
    zjsxwc  
       Oct 12, 2019 via Android
    两次 sql 呗
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   6099 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 80ms · UTC 02:04 · PVG 10:04 · LAX 19:04 · JFK 22:04
    ♥ Do have faith in what you're doing.