我正在努力查询存在一些空值的查询,在我的CASE语句中,未处理NULL值的测试。我尝试过以不同的顺序订购测试,但似乎没有什么不同。

SELECT Title, library.LibraryID, Registered
FROM libraries
LEFT JOIN
(SELECT LibraryID,UserID,
        (CASE
>>>                WHEN UserID IS NULL THEN "False"     <<<<<<<< PROBLEM
               WHEN UserID=1 THEN "YES! Registered"
                   ELSE "Not Registered"
     END) AS Registered
FROM librariesandmembers WHERE UserID=1) AS myAlias
ON libraries.LibraryID = myAlias.LibraryID');


然后我尝试了

WHEN USerID<>1 THEN "False"


但这并没有任何改变。

这是一个PHP / MySQL应用程序。 phpmyAdmin中的结果表明,我的查询结果在希望“ False”出现的地方产生了NULLS。

我想念什么?一定很明显,但我看不到。

[编辑]让我尝试用这种方式解释目标:我想列出所有(例如5个)库,并在其旁边显示用户是“是!已注册”或“未注册”的结果。 libraryandmembers表中可能有也可能没有相应的条目。因此是NULL问题。

最佳答案

这是您的查询:

SELECT Title, l.LibraryID, Registered
FROM libraries lLEFT JOIN
      (SELECT LibraryID, UserID,
              (CASE WHEN UserID IS NULL THEN "False"     <<<<<<<< PROBLEM
                    WHEN UserID=1 THEN "YES! Registered"
                   ELSE "Not Registered"
               END) AS Registered
       FROM librariesandmembers
       WHERE UserID = 1
      ) AS myAlias
      ON l.LibraryID = myAlias.LibraryID;


在子查询中,userId始终具有1的值,因此case语句仅显示'YES! Registered'。您想将其移到外部。为了获得相同的效果,条件UserId=1必须移到on子句:

SELECT Title, l.LibraryID, Registered,
       (CASE WHEN myalias.UserID IS NULL THEN 'False'
             WHEN myalias.UserID = 1 THEN 'YES! Registered'
             ELSE 'Not Registered'
        END) AS Registered
FROM libraries l LEFT JOIN
     librariesandmembers myalias
      ON l.LibraryID = myAlias.LibraryID and
         myalias.UserID = 1;

10-07 18:09