如何使用 UNION 从数据库中获取一个共同值
上图中的2条记录来自Db,上表中的约束是(SID和LINE_ITEM_ID), SID 和 LINE_ITEM_ID 两列都用于查找唯一记录。
我的问题: 我正在寻找一个查询,它应该根据条件从数据库中获取记录 如果我搜索 PART_NUMBER = 'PAU43-IMB-P6' 1. 如果搜索 PART_NUMBER = 'PAU43-IMB-P6',则无论该项目属于哪个 SID,只要在 SID =1 或 SID = 2 下只记录了一条记录,它都应该从数据库中获取一条记录。 2. 如果有 2 个项目,其中一个在 SID=1 中,另一个在 SID=2 中,则它应该仅在搜索 PART_NUMBER = 'PAU43-IMB-P6' 时从数据库中获取 SID = 2 下的一条记录。
我正在寻找一个查询,该查询将根据SID 1和2搜索给定的part_number,并且它应该返回SID = 2下的值,并且仅当SID = 2下没有记录时才可以返回SID = 1下的值(查询必须承受百万条记录搜索的负载)。
谢谢
2 records in above image are from Db, in above table Constraint are (SID and LINE_ITEM_ID),
SID and LINE_ITEM_ID both column are used to find a unique record.
My issues :
I am looking for a query it should fetch the recored from DB depending on conditions
if i search for PART_NUMBER = 'PAU43-IMB-P6'
1. it should fetch one record from DB if search for PART_NUMBER = 'PAU43-IMB-P6', no mater to which SID that item belong to if there is only one recored either under SID =1 or SID = 2.
2. it should fetch one record which is under SID = 2 only, from DB on search for PART_NUMBER = 'PAU43-IMB-P6', if there are 2 items one in SID=1 and other in SID=2.
i am looking for a query which will search for a given part_number depending on Both SID 1 and 2, and it should return value under SID =2 and it can return value under SID=1 only if the there are no records under SID=2 (query has to withstand a load of Million record search).
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我理解正确的话,对于每个考虑的
LINE_ITEM_ID
,您只想返回SID
值最大的那个。这是一个常见的需求,并且与 SQL 中的大多数内容一样,可以用多种不同的方式编写;最佳性能取决于许多因素,其中最重要的是您正在使用的 SQL 产品。这是一种可能的方法:
也就是说,我不记得见过依赖于 UNION 关系运算符的方法。您可以使用 INTERSECT 关系运算符轻松重写上面的内容,但它会更冗长。
If I understand correctly, for each considered
LINE_ITEM_ID
you want to return only the one with the largest value forSID
. This is a common requirement and, as with most things in SQL, can be written in many different ways; the best performing will depend on many factors, not least of which is the SQL product you are using.Here's one possible approach:
That said, I don't recall seeing one that relies on the
UNION
relational operator. You could easily rewrite the above using theINTERSECT
relational operator but it would be more verbose.就我而言,它的工作原理如下:
此查询解决了我的问题............
Well in my case it worked something like this:
This query solved my issue..........