简体   繁体   中英

One to many relationship in SQL Server query

I have two tables in SQL Server Orders and OrderDetails .

  • Orders contains the OrderID and etc.
  • OrderDetails contain OrderID , ItemID , Quantity and etc.

These two tables have a one-to-many relationship. One order can have many items.

What is the best way to retrieve records from these 2 table, so that when I display the records in my ASP page, it will have the following tabular format?

OrderID ItemID Quantity
    1    156     1
    2    156     2
         150     1
         188     1
    3    245     1
         344     1

The easiest is to have a query to retrieve the details from the OrderDetails table inside the main loop, but this will be very resource intensive.

Is there a better way to achieve this?

The database is in SQL Server and my page is in classic ASP.

Thank you.

SQL:

select    o.OrderID, d.ItemID, d.Quantity
from      Orders o
          inner join OrderDetails d on o.OrderID = d.OrderID
order by  o.OrderID, d.ItemID

ASP:

store the last OrderID in a variable and whenever it's different than the last time print it, otherwise print an empty <td>

<% 
set lastId = -1
do while not objRS.EOF 
%>
  <tr>
<% if lastId <> objRs("OrderID") then %>
    <td><%= objRs("OrderID") %></td>
<% else %>
    <td></td>
<% end if %>
    <td><%= objRs("ItemID") %></td>
    <td><%= objRs("Quantity") %></td>
  </tr>
<% 
lastId = objRs("OrderID")
loop %>

You have 3 options here:

(a) Create a stored procedure that 'flattens' the relationship down into single rows, your presentation layer can then selectively make a choice on what to hide or display. Effectively your query should return the following data into a business object:

 OrderID ItemID Quantity 1 156 1 2 156 2 2 150 1 2 188 1 3 245 1 3 344 1 

Your UI must then handle the complexity of display the parent child relationship and hiding duplicate orders.

(b) Use an ORM like Entity Framework or nHibernate to populate a parent / child object model that reflects your table and relationship structure. That way the presentation layer can just write out the object model (iterate through each parent and child collection).

(c) Load each orders details collection via a separate query in a loop for each order.

Option (c) is the least preferred as it scales terribly because the number of database calls directly correlates to the number of orders.

Option (b) is the best approach if you are using an ORM but if not a simple solution (a) is a good method to quickly retrieve the data in one go via a stored procedure.

Bear in mind that if you have large data-sets you may want to consider implementing paging as performance will degrade as you retrieve more data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM