MySQL嵌套查询:从两个表返回单行和多行查询

发布于 2024-11-03 05:10:14 字数 213 浏览 1 评论 0原文

我有两个表:发票和费用,具有一对多关系。 (简化)发票有:id、描述、日期作为字段,费用有:id、id_invoice、价格、数量、日期作为字段

对于发票生成,我需要发票表中的信息,例如 id=1 以及来自的所有信息费用表,其中 id_invoice=1 (因此发票中的一行和费用中的多行)

目前我有两个单独的查询,但我想知道是否可以在单个查询中执行此操作?

谢谢

I have two tables: invoice and charges, with a one-to-many relationship. (simplified) invoice has: id, description, date as fields and charges has: id, id_invoice, price, qty, date as fields

For invoice generation I need the info from the invoice table where e.g. id=1 and also all the info from the charges table where id_invoice=1 (so one row from invoice and multiple rows from charges)

At the moment I've got two separate queries but I was wondering if it was possible to do this in a single query?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

把时间冻结 2024-11-10 05:10:14

您可以在连接 invoice.id=charges.id_invoice 的两个表之间执行简单的 JOIN

对于同一张发票上的每项费用,发票字段将返回相同的结果,但它允许您在单个查询中获取数据。

该查询看起来像:

SELECT * FROM invoice i, charges c WHERE i.id=c.id_invoice ORDER BY i.id;

You could just do a simple JOIN between the two tables joining on invoice.id=charges.id_invoice

The invoice fields would be returned identically for every charge on the same invoice but it'd allow you to fetch the data in a single query.

The query would look something like:

SELECT * FROM invoice i, charges c WHERE i.id=c.id_invoice ORDER BY i.id;
千秋岁 2024-11-10 05:10:14

对于您的需求,左连接似乎更好。例如:

SELECT * FROM invoice i LEFT JOIN charges c ON i.id=c.id_invoice ORDER BY i.id;

可以找到 SQL 连接的一个很好的说明

For your needs, a LEFT JOIN seems better. Ex:

SELECT * FROM invoice i LEFT JOIN charges c ON i.id=c.id_invoice ORDER BY i.id;

A nice illustration of SQL joins can be found here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文