简体   繁体   中英

SQL Best way to return data from one table along with mapped data from another table

I have the following problem.

I have a table Entries that contains 2 columns:

  • EntryID - unique identifier
  • Name - some name

I have another EntriesMapping table ( many to many mapping table) that contains 2 columns :

  • EntryID that refers to the EntryID of the Entries table
  • PartID that refers to a PartID in a seprate Parts table.

I need to write a SP that will return all data from Entries table, but for each row in the Entries table I want to provide a list of all PartID 's that are registered in the EntriesMapping table.

My question is how do I best approach the deisgn of the solution to this, given that the results of the SP would regularly be processed by an app so performance is quite important.

1. Do I write a SP that will select multiple rows per entry - where if there are more than one PartID 's registered for a given entry - I will return multiple rows each having the same EntryID and Name but different PartID 's

OR

2. Do I write a SP that will select 1 row per entry in the Entries table, and have a field that is a string/xml/json that contains all the different PartID 's.

OR

3. There is some other solution that I am not thinking of?

Solution 1 seems to me to be the better way to go, but I will be passing lots of repeating data.

Solution 2 wont pass extra data, but the string/json/xml would need to be processed additionally, resuling in larger cpu time per item.

PS: I feel like this is quite a common problem to solve, but I was unable to find any resource that can provide common solutions or some pros/cons to different approaches.

I think you need simple JOIN :

SELECT e.EntryId, e.Name, em.PartId
FROM Entries e
JOIN EntriesMapping em ON e.EntryId = em.EntryId

This will return what you want, no need for stored procedure for that.

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