【问题标题】:Implement foreach logic in SQL在 SQL 中实现 foreach 逻辑
【发布时间】:2021-04-04 15:21:13
【问题描述】:

我有一张这样的桌子Fruit

Name Property Value
Apple Price $5
Apple Color Red
Apple Quantity 20
Pear Price $5
Pear Color Kelly
Pear Weight 50g
Pear Quality Good

现在我想在PropertyValue 中选择与Apple 不同的Pear 的所有记录(结果将是最后3 行)

在 C# 中是

foreach(var apple in apples)
{
   var result = pears.All(pear => pear.Property != apple.Property && pear.Value != apple.Value)
}

在 SQL Server 中我尝试了这个但失败了:

    Select * from Fruit where Name = 'Pear'
and exists
(select 1 from Fruit t where t.Name = 'Apple'
and t.Property <> Fruit.Property
and t.Value <> Fruit.Value)

我应该如何更正 SQL 语句?谢谢。

【问题讨论】:

  • 这是一个非常糟糕的规范化表!如果这是来自现实生活中的应用程序,你真的应该做点什么。
  • 但苹果可以是红色和绿色(以及其他颜色)。你怎么知道什么财产属于另一个人?您的设计需要在这里修复。
  • 道歉。那是我第一次在这里使用 Table。当我预览它时,它看起来还不错。但是在我发布这个问题后丢失了格式。感谢您的评论和编辑。
  • @GertArnold 不是在谈论您如何呈现表格,他们是在说您在实际数据库中的设计存在缺陷。
  • EAV 再次来袭!如果您正在设计自己的数据库,请研究该术语以了解后果以及尝试从中提取有意义的信息时将面临的非常实际的问题。

标签: c# sql sql-server linq


【解决方案1】:

你可以使用not exists:

select f.*
from fruit f
where f.name = 'Pear' and
      not exists (select 1
                  from fruit f2
                  where f2.name = 'Apple' and
                        f2.property = f.property and
                        f2.value = f.value
                 );

【讨论】:

    猜你喜欢
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多