【问题标题】:Can we run subquery multiple time for outer query我们可以为外部查询多次运行子查询吗
【发布时间】:2021-07-18 10:32:05
【问题描述】:

我会尽力解释我想要什么。如果你能建议我一个更好的问题标题,那就太好了。

在我的存储过程中,我传递了一个包含AttributeIdAttributeValueId 的用户定义表,我想检索该用户定义表的基础MappedAttributeId

例如我想选择值MappedAttributeId = 99,因为在用户定义的表中我通过了

AttributeId    AttributeValueId
------------------------------
    84             156
    85             158

我在上面附加的表与我的用户定义表之间使用连接,但它会为我返回多个结果,其中 AttributeValueId 为 156 的所有属性 ID 84 和 AttributeValue 为 156 的所有属性 ID 85

但我想要 MappedAttributeId where AttributeId = 84 AttributeValueId = 156 and AttributeId = 85 AttributeValueId = 158

我想在外部查询中使用 MappedAttributeId,并且我在子查询中使用连接,所以无论如何都可以在不使用游标的情况下编写此查询。

好的,这是我传递给存储过程的用户定义表:

declare @p4 [Order].ProductSelectedAttributes
insert into @p4 values(84,156)
insert into @p4 values(85,158)

上面参数的第一个值是AttributeId,第二个是AttributeValueId

我写的查询是

Select MappedAttributeId 
from [Product].tblMappedAttributesDetail mad -- This is the table in the first picture on top
join @p4 psa on psa.attrId = mad.AttributeId and psa.attrValId = mad.AttributeValueId

此查询返回三个值,即 99,99,100,因为我的参数 (84,156) 中的第一行匹配 MappedAttributeId 为 99 的表中的第一行和 MappedAttributeId 为 100 的第三行,以及我的第二行参数 (85,158) 匹配表中 MappedAttributeId 为 100 的第二行。我可以使用 GroupBy 删除 重复 99 值,但如何从结果中排除 100?

但我只想要 MappedAttributeId 99,因为它匹配我的参数 (84,156) 和 (85,158) 的两行。我不想要 MappedAttributeId 100,因为它只匹配 (85,158) 而不是另一行 (84,156)

【问题讨论】:

  • 编辑您的问题并明确您想要的结果。
  • JOIN 不就是你想要的吗?
  • @GordonLinoff 我想从图片中选择 MappedAttributeId (AttributeId 和 AttributeValueId 匹配用户定义表中的所有项目)例如,您可以看到 MappedAttributeId 99 在表中出现两次,但 AttributeId 和 AttributeValueId 不同现在在每一行中,当我的用户定义表包含 2 行,值分别为 84,156 和 85,158 时,我想从 MappedAttributeId 中选择 99
  • @Serg 有点不同。你可以阅读我刚刚添加的评论,它可以解释我想要什么

标签: sql sql-server database stored-procedures database-cursor


【解决方案1】:

我刚刚添加了 group by 并使用 Have 进行计数,它起作用了。感谢大家的帮助。

Select MappedAttributeId
from [Product].tblMappedAttributesDetail mad
join @p4 psa on psa.attrId = mad.AttributeId and psa.attrValId = mad.AttributeValueId
group by MappedAttributeId
Having (Select Count(1) from @p4) = Count(1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    相关资源
    最近更新 更多