0

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

1
  • Could we see those queries please ? Commented Apr 23, 2011 at 23:30

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that makes sense. Would this be more efficient from a DB load perspective than two separate queries?
It's hard to say. There'll be less work for the client (there's only one query instead of two) but there's more overall data which could create more network traffic. I suspect there's very little in it.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.