我有以下SQL,我正在try 将其转换为LINQ:

SELECT f.value
FROM period as p 
LEFT OUTER JOIN facts AS f ON p.id = f.periodid AND f.otherid = 17
WHERE p.companyid = 100

我见过左外连接的典型实现(如into x from y in x.DefaultIfEmpty()等),但不确定如何引入其他连接条件(AND f.otherid = 17)

EDIT

为什么AND f.otherid = 17条件是JOIN的一部分,而不是WHERE子句的一部分?

不幸的是:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in fg.DefaultIfEmpty()
where p.companyid == 100 && fgi.otherid == 17
select f.value

似乎相当于:

SELECT f.value
FROM period as p 
LEFT OUTER JOIN facts AS f ON p.id = f.periodid 
WHERE p.companyid = 100 AND f.otherid = 17

这不是我想要的.

推荐答案

在拨打DefaultIfEmpty()之前,您需要介绍您的加入条件.我只会使用扩展方法语法:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in fg.Where(f => f.otherid == 17).DefaultIfEmpty()
where p.companyid == 100
select f.value

或者可以使用子查询:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in (from f in fg
             where f.otherid == 17
             select f).DefaultIfEmpty()
where p.companyid == 100
select f.value

Sql相关问答推荐

前面的语句不喜欢AND LIKE?当try 更新使用ID和日期过滤的表时

转换表中的数据

SQL基于多个值 Select 单行

Redshift PL/pgSQL循环中的参数化列名

在查询Oracle SQL中创建替代ID

用于从第二个表中提取具有最小最终价格值的记录的SQL查询

在Netezza SQL中将字符DataType转换为整型DataType

postgres中的条件索引和触发器

在 PostgreSQL 中使用 ltree 列进行累积

如何创建snowflake表(动态查找数据类型)并从阶段加载(AWS S3)?

根据标识符将两行合并为一行

连续天跟踪购买情况(将标记返回到另一列?)

试图找到两个身份列表的交集(列表的长度不同),但获取列 id 不明确?

Postgres更新增量之间的差异

在Snowflake中如何使用SQL对版本字符串进行排序?

如何在插入时将字符串'03-January-2023'转换为日期时间

编写查询以根据级别 (p2) 返回父位置

SQL Server 分区和 Run Case 语句

SQL 计数和过滤查询优化

如何比较同一张表中的行并进行相应更新