我有一种情况需要从'MEMBER'表中提取成员记录。我需要检索姓氏,名字,关系,入职日期,会员ID,电子邮件和网站ID。标准是'P',siteid为'111'和非空白电子邮件地址的关系,我需要排除两个子集。子集A具有上述所有条件以及用户定义字段ID为26的用户定义字段,用户定义字段值为“否”且输入日期超过6天前。子集B具有相同的主要标准,但是输入日期超过2周,用户定义字段为25,使用的已定义字段值为25.用户定义的字段和值存储在单独的表(MEMBERUDFS)中。会员数据。棘手的部分是,如果用户未设置用户定义字段的值,则MEMBERUDFS表上没有条目。这两个表与memid的键相关联。
这是我到目前为止所做的,并没有排除A组,我没有尝试添加逻辑来排除B组。任何帮助都将不胜感激!!! :
SELECT MEMBERS.scancode,
MEMBERS.memid,
MEMBERS.fname,
MEMBERS.lname,
MEMBERS.relationship,
MEMBERS.STATUS,
MEMBERS.email,
MEMBERS.entrydate,
SITES.sitename
FROM MEMBERS
INNER JOIN SITES ON MEMBERS.siteid = SITES.siteid
LEFT OUTER JOIN MEMBERUDFS ON MEMBERS.memid = MEMBERUDFS.memid
INNER JOIN MEMBERUDFSETUPS ON MEMBERUDFS.udfid = MEMBERUDFSETUPS.udfid
WHERE (MEMBERS.relationship = 'P')
AND (MEMBERS.email <> '')
AND (
MEMBERS.memid NOT IN (
SELECT MEMBERS_1.memid
FROM MEMBERS AS MEMBERS_1
INNER JOIN SITES AS SITES_1 ON MEMBERS_1.siteid = SITES_1.siteid
LEFT OUTER JOIN MEMBERUDFS AS MEMBERUDFS_1 ON MEMBERS_1.memid = MEMBERUDFS_1.memid
INNER JOIN MEMBERUDFSETUPS AS MEMBERUDFSETUPS_1 ON MEMBERUDFS_1.udfid = MEMBERUDFSETUPS_1.udfid
WHERE (MEMBERS_1.relationship = 'P')
AND (MEMBERS_1.email <> '')
AND (MEMBERUDFS_1.udfid = '26')
AND (MEMBERUDFS_1.udfvalue = 'No')
AND (MEMBERS_1.entrydate < DATEADD(DAY, 6, GETDATE()))
AND (MEMBERS_1.siteid = @rvSite)
)
)
AND (MEMBERS.siteid = @rvSite)
答案 0 :(得分:0)
你能用这种方式改写查询:
SELECT MEMBERS.scancode,
MEMBERS.memid,
MEMBERS.fname,
MEMBERS.lname,
MEMBERS.relationship,
MEMBERS.STATUS,
MEMBERS.email,
MEMBERS.entrydate,
SITES.sitename
FROM MEMBERS
INNER JOIN SITES ON MEMBERS.siteid = SITES.siteid
LEFT OUTER JOIN MEMBERUDFS ON MEMBERS.memid = MEMBERUDFS.memid
INNER JOIN MEMBERUDFSETUPS ON MEMBERUDFS.udfid = MEMBERUDFSETUPS.udfid
WHERE (MEMBERS.relationship = 'P')
AND (MEMBERS.email <> '')
AND (MEMBERS.siteid = @rvSite)
AND NOT (MEMBERS.entrydate < DATEADD(DAY, 6, GETDATE()) AND EXISTS
(SELECT memid FROM MEMBERUDFS WHERE (MEMBERUDFS.udfid = '26')
AND (MEMBERUDFS.udfvalue = 'No')
AND (MEMBERUDFS.memid = MEMBERS.memid)))
答案 1 :(得分:0)
看起来你应该可以在这里使用NOT EXISTS并从主查询中删除UDF表,因为你没有从中选择任何东西。
SELECT MEMBERS.scancode,
MEMBERS.memid,
MEMBERS.fname,
MEMBERS.lname,
MEMBERS.relationship,
MEMBERS.STATUS,
MEMBERS.email,
MEMBERS.entrydate,
SITES.sitename
FROM MEMBERS
INNER JOIN SITES ON MEMBERS.siteid = SITES.siteid
WHERE (MEMBERS.relationship = 'P')
AND (MEMBERS.email <> '')
AND (MEMBERS.siteid = @rvSite)
AND NOT EXISTS (
SELECT 1
FROM MEMBERUDFS AS MEMBERUDFS_1 ON MEMBERS_1.memid = MEMBERUDFS_1.memid
INNER JOIN MEMBERUDFSETUPS AS MEMBERUDFSETUPS_1 ON MEMBERUDFS_1.udfid = MEMBERUDFSETUPS_1.udfid
WHERE MEMBERS.memid = MEMBERUDFS_1.memid
AND (MEMBERUDFS_1.udfid = '26')
AND (MEMBERUDFS_1.udfvalue = 'No')
AND (MEMBERS.entrydate < DATEADD(DAY, 6, GETDATE()))
)