检索与变量匹配的父 类 的子实体列表

Retrieve a list of child entities for parent classes that match variables

我一直在使用 Entity Framework 和 LINQ 开发 XML 解析系统,现在我在翻译以前的 SQL 查询时遇到了一些问题,其中 table不是标准化格式。

我有以下结构:

1. Message                     (Each message type has one to many messagetype341s)
2. MessageType341              (Each messagetype341 has 1 to many meters)       
3. Meter                       (Each meter has 2 channel informations)
4. ChannelInformation          (Each channel information has 48 interval informations)
5. Interval Information

ReadDateCustomerNo在MessageType341级别。我正在尝试编写 sequel,其中我将 CustomerNo 和 ReadDate 作为变量放入其中,然后基于中列出的 messagetype341s 的 return 然后检索随后的仪表、通道信息和间隔信息相关消息类型 341s

我试过以下方法:

SELECT c.SerialNumber,
       b.ReadDate,
       d.RegisterTypeCode,
       e.IntervalStatusCode,
       d.UOM_Code,
       e.IntervalPeriodTimestamp,
       e.IntervalValue
FROM   MarketMessage AS a,
       MessageType341 AS b,
       Meter AS c,
       ChannelInformation AS d,
       IntervalInformation AS e
WHERE  b.CustomerNo = '12348750528'
       AND b.ReadDate >= '01 nov 2014'
       AND b.ReadDate <= '30 nov 2014'
ORDER  BY b.ReadDate 

但是 returning 值似乎与我的预期值不匹配,我是不是用错了方法?

据我了解,您需要使用 LEFT jons。

select c.SerialNumber, b.ReadDate, d.RegisterTypeCode, e.IntervalStatusCode, d.UOM_Code,   e.IntervalPeriodTimestamp, e.IntervalValue
from MarketMessage as a LEFT JOIN MessageType341 as b ON a.PK = b.FK
LEFT JOIN  Meter as c ON b.PK = c.FK
LEFT JOIN  ChannelInformation as d ON c.PK = d.FK
LEFT JOIN  IntervalInformation as e ON d.PK = e.FK
where b.CustomerNo = '12348750528'
and b.ReadDate BETWEEN '01 nov 2014' AND and b.ReadDate <= '30 nov 2014'
order by b.ReadDate

其中:

PK = 主键

FK = 外键

各类型join的区别,请看:Visual Representation of SQL Joins

您正在使用旧的 JOIN 语法,并且没有过滤这些结果:

SELECT *
FROM Table1,Table2

Returns Table1 中的每一行与 Table2 中的每一行配对,CROSS JOIN 或笛卡尔积。

您可以根据关系过滤结果,即:WHERE Table1.ID = Table2.Parent_ID,但最好使用标准 JOIN 语法:

SELECT c.SerialNumber, b.ReadDate, d.RegisterTypeCode, e.IntervalStatusCode, d.UOM_Code,   e.IntervalPeriodTimestamp, e.IntervalValue
FROM MarketMessage as a
JOIN MessageType341 as b
  ON a.ID = b.Parent_ID
JOIN Meter as c
  ON b.ID = c.Parent_ID
JOIN ChannelInformation as d
  ON c.ID = d.Parent_ID
JOIN IntervalInformation as e
  ON d.ID = e.Parent_ID
WHERE b.CustomerNo = '12348750528'
  AND b.ReadDate >= '01 nov 2014'
  AND b.ReadDate <= '30 nov 2014'
ORDER BY b.ReadDate

如果您有一些没有子项的记录,您可以更改为 LEFT JOIN 以带回所有记录,无论它们是否具有所有级别的信息。