nyse
V2EX  ›  数据库

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

  •  
  •   nyse · Oct 11, 2019 · 3867 views
    This topic created in 2580 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
    eason1874
    Oct 11, 2019
    1
    直接参考 WordPress 分类关系表设计
    aragakiyuii
    aragakiyuii
    Oct 11, 2019 via Android
    2
    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
    ipiao
    Oct 11, 2019
    3
    建议写 2 条 sql,拒绝 join
    Doldrums
    Doldrums
    Oct 11, 2019
    4
    对 B 表 ROW_NUMBER() over(partition...)排序之后 leftjoin 限制 B.rowNum=1
    bumz
    bumz
    Oct 11, 2019 via iPhone
    5
    select a.*, b.content from a, b where a.id = b.aid limit 1;

    没测
    想时间倒序就加 order by
    bumz
    bumz
    Oct 11, 2019 via iPhone
    6
    @bumz 看错,忽略
    QiuSe
    QiuSe
    Oct 11, 2019
    7
    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
    Caballarii
    Oct 11, 2019
    8
    建议分开写 sql,多不了几条,A 表多了就分页查
    wangyzj
    wangyzj
    Oct 11, 2019
    9
    content 不应该是属于 a 表才对么
    nyse
    nyse
    OP
    Oct 11, 2019
    10
    @wangyzj #9 不是,A 表一个条目对应 B 表多条,但只要选取 B 表其中一条
    zjsxwc
    zjsxwc
    Oct 12, 2019 via Android
    11
    两次 sql 呗
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5288 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 01:26 · PVG 09:26 · LAX 17:26 · JFK 20:26
    ♥ Do have faith in what you're doing.