如何从表 2 中创建总和并显示数据表 1 和表 2

How create sum from tabel 2 and show data tabel 1 and tabel 2

表 A:

id invoice
1 001
2 002

表 B:

id invoiceId price
1 1 10
2 1 20
3 1 10
4 2 15

期待

id invoice total count
1 001 10 40
2 001 20 40
3 001 10 40
4 002 15 15

我的一对多关系。 因为我需要一列名称计数基于表格 B sum(price) 并按 invoiceId 分组 如何使其 mysql 查询高于 tabel A 和 B 的预期?

在 MySQL 8+ 上,我们可以使用分析函数在没有子查询的情况下处理此问题:

SELECT
    b.id,
    a.invoice,
    b.price AS total,
    SUM(b.price) OVER (PARTITION BY a.id) AS count
FROM TableB b
LEFT JOIN TableA a
    ON a.id = b.aid;

在 MySQL 的早期版本中,或者如果您是从不喜欢分析函数的 ORM 层执行此操作,我们也可以尝试使用连接来聚合计数:

SELECT
    b1.id,
    a.invoice,
    b1.price AS total,
    COALESCE(b2.count, 0) AS count
FROM TableB b1
LEFT JOIN TableA a
    ON a.id = b1.aid
LEFT JOIN
(
    SELECT aid, SUM(price) AS count
    FROM TableB
    GROUP BY aid
) b2
    ON b2.aid = b1.aid;