0

我要求我们的系统列出所有已发布优惠券的成员和所有尚未发布优惠券的用户。我制作了一个 SQL 脚本来提取已发布优惠券的成员列表。这是代码:

SELECT DISTINCT
b.Email,
b.FirstName,
b.LastName,
b.MemberDisplayName AS DisplayName,
b.MemberID
FROM ClassAd a
INNER JOIN Member b ON b.MemberID = a.MemberID
WHERE a.PostType = 'CPN'
AND DATEDIFF(d, 0, GETDATE()) <= a.ExpirationDate
AND a.Viewable = 'Y'
AND b.SystemID = 1
AND b.Claimed = 'Y'
AND b.Email IS NOT NULL

如何反转此脚本,使其仅拉出尚未发布优惠券的用户..?

任何帮助将不胜感激。

4

5 回答 5

2

外连接和 null 测试与连接相反
注意您需要外连接才能使用(而不是在哪里)

SELECT DISTINCT
b.Email,
b.FirstName,
b.LastName,
b.MemberDisplayName AS DisplayName,
b.MemberID
FROM Member b  
Left Outer JOIN ClassAd a
  ON b.MemberID = a.MemberID
 AND a.PostType = 'CPN'
 AND DATEDIFF(d, 0, GETDATE()) <= a.ExpirationDate
 AND a.Viewable = 'Y'
 AND b.SystemID = 1
 AND b.Claimed = 'Y'
 AND b.Email IS NOT NULL
where a.MemberID is null  

你可以移动

 AND b.SystemID = 1
 AND b.Claimed = 'Y'
 AND b.Email IS NOT NULL

进入 where 但在这种格式下,查询优化器有机会在连接之前消除行

于 2013-10-30T13:44:54.517 回答
2

发布优惠券的会员列表。

SELECT Email
     , FirstName
     , LastName
     , MemberDisplayName As DisplayName
     , MemberID
FROM   Member
WHERE  SystemID = 1
AND    Claimed = 'Y'
AND    Email IS NOT NULL
AND    EXISTS (
         SELECT *
         FROM   ClassAd
         WHERE  PostType = 'CPN'
         AND    ExpirationDate >= DateDiff(dd, 0, Current_Timestamp)
         AND    Viewable = 'Y'
         AND    MemberID = Member.MemberID
       )

为了颠倒逻辑,将其变成一个简单的案例NOT EXISTS

于 2013-10-30T13:47:44.717 回答
1

这样的事情(未经测试)应该这样做:

SELECT DISTINCT
b.Email,
b.FirstName,
b.LastName,
b.MemberDisplayName AS DisplayName,
b.MemberID
FROM Member b
WHERE b.MemberID NOT IN 
     (SELECT a.MemberID 
        FROM ClassAd a
       WHERE a.PostType = 'CPN'
         AND DATEDIFF(d, 0, GETDATE()) <= a.ExpirationDate
         AND a.Viewable = 'Y')
AND b.SystemID = 1
AND b.Claimed = 'Y'
AND b.Email IS NOT NULL
于 2013-10-30T13:32:08.000 回答
1

假设有一张优惠券由表 ClassAd 表示,您可以使用 NOT IN 和子查询。

SELECT DISTINCT
b.Email,
b.FirstName,
b.LastName,
b.MemberDisplayName AS DisplayName,
b.MemberID
FROM Member b 
WHERE
b.memberID NOT IN (SELECT a.MemberID FROM ClassAd a WHERE  a.PostType = 'CPN' AND DATEDIFF(d, 0, GETDATE()) <= a.ExpirationDate AND a.Viewable = 'Y')
AND b.SystemID = 1
AND b.Claimed = 'Y'
AND b.Email IS NOT NULL
于 2013-10-30T13:34:07.543 回答
0
SELECT *
FROM @Member a
LEFT JOIN @ClassAd b 
    ON a.MemberId = b.MemberId AND b.PostType = 'CPN'
        AND b.ExpirationDate >= GETDATE()
        AND b.Viewable = 'Y'
WHERE b.MemberId IS NULL
AND a.SystemId = 1
AND a.Claimed = 'Y'
于 2013-10-30T13:48:26.780 回答