【发布时间】:2020-08-03 07:58:17
【问题描述】:
我有一个带有这样“字典”的数据库:
Id (INT) | Key (VARCHAR) | Value (VALUE) | ForeignKey (INT?)
------------------------------------------------------------
1 | foo | bar | 23
2 | bar | foo | NULL
3 | foobar | value | NULL
4 | foobar | othervalue | 47
现在我想获取特定外键的所有键和值,以及所有为 NULL 的外键,因此结果如下所示:
ForeignKey = 23: ForeignKey = 47:
foo | bar bar | foo
bar | foo foobar | othervalue
foobar | value
最初我尝试过这种方法:
dbContext.Table
.Where(t => t.ForeignKey == 47 || t.ForeignKey == null)
但这给了我两次foobar。
然后我考虑了多个请求并将结果联合起来:
var t1 = _dbContext.Table
.Where(t => t.ForeignKey == 47);
var t2 = _dbContext.Table
.Where(t => t.ForeignKey == null && !t1.Any(tt => tt.Key == t.Key));
var final = t1.Union(t2);
这看似可行,但它创建的 SQL(粗略)似乎过多,其中包含三个 SELECT、三个 WHERE 和一个 UNION
SELECT [t1].[Id], [t1].[Key], [t1].[Value], [t1].ForeignKey
FROM [Table] AS [t1]
WHERE [t1].[ForeignKey] = 47
UNION
SELECT [t2].[Id], [t2].[Key], [t2].[Value], [t2].ForeignKey
FROM [Table] AS [t2]
WHERE [t2].[ForeignKey] IS NULL AND NOT (EXISTS (
SELECT 1
FROM [Table] AS [t3]
WHERE ([t3].[ForeignKey] = 47) AND ([t3].[Key] = [t2].[Key])))
我只是有一种直觉,“必须有更好的方法”......所以,有吗?如何获取特定外键的键和值,以及尚未获取的 NULL 键?
【问题讨论】:
-
对于“ForeignKey = 47”,您还应该有“foobar | value”...
-
@TheImpaler 不,这就是重点......对于“ForeignKey = 47”我想要 value = “othervalue”的行
-
"...还有所有为 NULL 的外键..." - 你说过,所以应该包括“foobar | value”。我读错了什么?
-
按照我的理解,具有空外键的项目代表默认值。如果给定外部 ID 存在具有键的行,则该行的值优先。但是在没有覆盖该键的值的情况下,OP 希望结果中包含该键及其默认值。
-
@StriplingWarrior 这很有道理。不幸的是,我无法真正理解它。 30 分钟后投票结束,没有任何说明。
标签: sql linq optimization entity-framework-core