我在执行下面的linq查询时收到错误代码ORA-00907。它似乎是Oracle特有的。问题似乎是“分组依据”子查询。
假设我有这两个表:USER和ADDRESS,带有列: USER {userid,addressid}, ADDRESS {addressid,streetname}
表ADDRESS包含几个具有相同addressid的行,所以我想我想在addressid上对ADDRESS表(DISTINCT)进行分组,这样我只能在USER-table中获得一个与addressid的匹配,它也应该是一个LEFT加入,所以如果没有匹配,我仍然会收到USER记录。
我尝试过几种不同的方法,我的代码(例子):
List<MyObject> result =
(
from u in context.USER.Where(i => i.userid > 100)
join a in (from address in context.ADDRESS group address by address.addressid)
on u.addressid equals a.FirstOrDefault().addressid into joinedaddress
from lfjoinedaddress in joinedaddress.DefaultIfEmpty()
join email in context.EMAIL on u.userid equals email.userid into jemail
from lfjemail in jemail.DefaultIfEmpty()
select new MyObject()
{
UserId = u.userid,
StreetName = lfjoinedaddress.streetname,
UserEmail = lfjemail.emailaddress
}
).ToList();
有人知道如何通过重写查询来实现这一点,因此它可以对抗Oracle。
更新
这是生成的sql-query,但“email”除外:
SELECT
1 AS "C1",
"Extent1"."USERID" AS "USERID",
"Extent1"."ADDRESSID" AS "ADDRESSID"
FROM (SELECT
"USER"."USERID" AS "USERID",
"USER"."ADDRESSID" AS "ADDRESSIF",
FROM "EXT"."USER" "USER") "Extent1"
LEFT OUTER JOIN (SELECT "Distinct1"."ADDRESSID" AS "ADDRESSID1", "Limit1"."ADDRESSID" AS "ADDRESSID2", , "Limit1"."STREETNAME" AS "STREETNAME1"
FROM (SELECT DISTINCT
"Extent2"."ADDRESSID" AS "ADDRESSID"
FROM (SELECT
"ADDRESS"."ADDRESSID" AS "ADDRESSID",
"ADDRESS"."STREETNAME" AS "STREETNAME",
FROM "EXT"."ADDRESS" "ADDRESS") "Extent2" ) "Distinct1"
OUTER APPLY (SELECT "Extent3"."ADDRESSID" AS "ADDRESSID", "Extent3"."STREETNAME" AS "STREETNAME"
FROM (SELECT
"ADDRESS"."ADDRESSID" AS "ADDRESSID",
"ADDRESS"."STREETNAME" AS "STREETNAME",
FROM "EXT"."ADDRESS" "ADDRESS") "Extent3"
WHERE ("Distinct1"."ADDRESSID" = "Extent3"."ADDRESSID") AND (ROWNUM <= (1) ) ) "Limit1"
OUTER APPLY (SELECT "Extent4"."ADDRESSID" AS "ADDRESSID", , "Extent4"."STREETNAME" AS "STREETNAME"
FROM (SELECT
"ADDRESS"."ADDRESSID" AS "ADDRESSID",
"ADDRESS"."STREETNAME" AS "STREETNAME",
FROM "EXT"."ADDRESS" "ADDRESS") "Extent4"
WHERE ("Distinct1"."ADDRESSID" = "Extent4"."ADDRESSID") AND (ROWNUM <= (1) ) ) "Limit2" ) "Apply2" ON ("Extent1"."ADDRESSID" = "Apply2"."ADDRESSID2") OR (("Extent1"."ADDRESSID" IS NULL) AND ("Apply2"."ADDRESSID3" IS NULL))))
答案 0 :(得分:1)
DISTINCT 应用于元组,而不是元组中的单个值。如果表 ADDRESS 中的 STREETNAME 始终与 ADDRESSID 相同,那么您需要 DISTINCT 元组( ADDRESSID , STREETNAME )。您只需选择context.ADDRESS
的不同列作为子查询,然后省略.FirstOrDefault()
即可。
join a in
(
from address in context.ADDRESS
select new
{
address.addressid,
address.streetname
}
).Distinct()
on u.addressid equals a.addressid into joinedaddress
from lfjoinedaddress in joinedaddress.DefaultIfEmpty()
如果 STREETNAME 并非总是与 ADDRESSID 相同,那么您根本不需要 DISTINCT 。