我一直在使用Entity Framework和LINQ开发XML解析系统,现在我在翻译以前没有采用标准化格式的SQL查询时遇到了一些问题。
我有以下结构:
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
ReadDate 和 CustomerNo 处于MessageType341级别。我正在尝试写续集,其中我将CustomerNo和ReadDate作为变量,然后根据列出的messagetype341s的返回,然后检索相关messagetype341s的后续计量表,通道信息和间隔信息
我尝试了以下内容:
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
但它似乎没有返回与我的预期值匹配的值,我是否采用了错误的方式?
答案 0 :(得分:1)
根据我的理解,你需要使用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 =外键
每种类型的加入之间的差异,请参阅:Visual Representation of SQL Joins
答案 1 :(得分:1)
您使用旧的JOIN
语法,而不是过滤这些结果:
SELECT *
FROM Table1,Table2
返回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
以恢复所有记录,无论他们是否拥有各种级别的信息。