【问题标题】:MS SQL - Problem selecting a subset of recordsMS SQL - 选择记录子集的问题
【发布时间】:2011-01-19 19:32:35
【问题描述】:

我有一个 SQL 脑残时刻。当该产品的任何属性 ID 为特定值时,我正在尝试获取一组记录。

问题是,我需要获取同一产品的所有其他属性。

这是我的意思的说明:

有没有办法做到这一点?目前我正在这样做

select product_id
from mytable
where product_attribute_id = 154

但我显然只得到了一条记录:

任何帮助将不胜感激。我的 SQL 技能有点基础。

编辑

有一个条件我忘了提。有时我需要能够过滤两个属性 ID。例如,在上面的第一张图片中,较低的集合(产品 ID 31039)具有属性 id 395。我需要过滤 154、395。结果将不包括没有属性 id 的顶部集合(31046) 395.

【问题讨论】:

  • 没有道理为什么你只会得到一条记录。

标签: sql sql-server coldfusion


【解决方案1】:

我想这就是你要找的东西:

SELECT * myTable where Product_Id IN (SELECT Product_Id FROM MyTable WHERE Product_AttributeID = @parameterValue)

In English: Get me all the records that they product id is in the set of all product ids that their attribute id is equal to @parameterValue.

编辑:

SELECT * myTable where Product_Id IN (SELECT Product_Id FROM MyTable WHERE Product_AttributeID = @parameterValue1) AND Product_Id IN (SELECT Product_Id FROM MyTable WHERE Product_AttributeID = @parameterValue2)

应该可以的。

【讨论】:

  • 这绝对是在正确的轨道上。谢谢!我添加了一个需要过滤附加属性 ID 的编辑(对不起!)。我只需要内部查询的 OR 语句吗?
  • (关于我的最后一条评论)实际上我不能使用 or,因为我只需要找到两个属性 ID 的记录。
  • @jyoseph:内部查询将类似于(SELECT Product_Id FROM MyTable WHERE Product_AttributeID IN (154,395) GROUP BY Product_Id HAVING COUNT(DISTINCT Product_AttributeID) = 2)
  • @Chris:我查询的HAVING COUNT(DISTINCT Product_AttributeID) = 2 部分意味着两者都必须匹配。
  • 只是提个醒,4 年后的今天仍然在回顾这个答案。
【解决方案2】:

使用正确的连接,您可以链接回同一个表

select B.*
from mytable A
-- retrieve B records from A record link
inner join mytable B on B.product_id = A.product_id
where A.product_attribute_id = 154  -- all the A records

编辑:要获得具有 2 个属性的产品,您可以再次加入

select C.*
from mytable A
-- retrieve B records from A record link
inner join mytable B on B.product_id = A.product_id
inner join mytable C on C.product_id = A.product_id
where A.product_attribute_id = 154  -- has attrib 1
  AND B.product_attribute_id = 313  -- has attrib 2

【讨论】:

  • +1 这太棒了,我会试着绕开这个。它部分工作,但还有一些其他的滑稽动作会导致问题。
猜你喜欢
  • 2019-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-26
  • 1970-01-01
相关资源
最近更新 更多