简体   繁体   English

从一个表返回数据以及从另一个表映射数据的SQL最佳方法

[英]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: 我有一个 Entries包含2列:

  • EntryID - unique identifier EntryID唯一标识符
  • Name - some name Name -某些名称

I have another EntriesMapping table ( many to many mapping table) that contains 2 columns : 我还有另一个EntriesMapping 多对多映射表),其中包含2列:

  • EntryID that refers to the EntryID of the Entries table EntryID是指EntryID中的Entries
  • PartID that refers to a PartID in a seprate Parts table. PartID是指PartID在seprate Parts表。

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. 我需要写一个SP将从返回的所有数据 Entries表,但在每一行Entries表我想提供所有的列表 PartID是在注册的EntriesMapping表。

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. 我的问题是,鉴于SP的结果将由应用定期处理,因此如何最好地解决此问题,因此性能非常重要。

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 1.我是否编写了一个将为每个条目选择多行的SP-如果给定条目注册了多个PartID ,则我将返回多行,每行具有相同的EntryIDName但具有不同的PartID

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. 2.我是否编写了一个SP,它将在Entries表中的每个条目中选择1行 ,并具有一个字符串/ xml / json字段,其中包含所有不同的PartID

OR 要么

3. There is some other solution that I am not thinking of? 3.我没有想到其他解决方案吗?

Solution 1 seems to me to be the better way to go, but I will be passing lots of repeating data. 在我看来, 解决方案1是更好的方法,但是我将传递大量重复数据。

Solution 2 wont pass extra data, but the string/json/xml would need to be processed additionally, resuling in larger cpu time per item. 解决方案2不会传递额外的数据,但是string / json / xml将需要额外处理,从而导致每个项目的CPU时间更长。

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. PS:我觉得这是一个很普遍的问题,但是我找不到任何可以提供通用解决方案或不同方法利弊的资源。

I think you need simple JOIN : 我认为您需要简单的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. 这将返回您想要的内容,不需要存储过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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