MySQL嵌套查询:从两个表返回单行和多行查询
我有两个表:发票和费用,具有一对多关系。 (简化)发票有: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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在连接
invoice.id=charges.id_invoice
的两个表之间执行简单的JOIN
,对于同一张发票上的每项费用,发票字段将返回相同的结果,但它允许您在单个查询中获取数据。
该查询看起来像:
You could just do a simple
JOIN
between the two tables joining oninvoice.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:
对于您的需求,左连接似乎更好。例如:
可以找到 SQL 连接的一个很好的说明
For your needs, a LEFT JOIN seems better. Ex:
A nice illustration of SQL joins can be found here