I have a SQL question. I have a SQL Server database with 2 tables I want to grab data from. It's kind of similar to the database found here:
https://www.w3schools.com/sql/trysql.asp?filename=trysql_asc
Just the Customers
and Orders
table are relevant.
What I'd like to do is use a SQL query to list all of the customers, and below each customer, display all their respective orders.
Currently I'm doing something like this (in my classic ASP web page):
SELECT * FROM Customers ORDER BY CustomerName;
I'm then iterating through all the customers (returned records), and displaying them...but for each record/customer returned, I run this:
SELECT * FROM Orders WHERE CustID = " & rs("id")
Then iterate through those results to display all the open orders for that customer.
Basically it's 1 long page that shows all our 'customers' and each of their open 'orders'.
It's become fairly large/long, and is taking a bit longer than I'd like to load these days.
So again, I'm guessing I could do this more efficiently with a single SQL query to eliminate that 2nd trip to the database for each customer record?
I know didn't give a ton of detail here, but hopefully it makes sense. I didn't want to create a super long post/thread. I can definitely give more details if needed.
Thank you for reading!
2条答案
按热度按时间eagi6jfj1#
In order to avoid retrieving the customer data with each of their orders again and again, you can just run two queries, both ordered by customer name:
Customers
Orders
e5nqia272#
seems you need simple join