返回带有NULL值的必要列的空行

时间:2013-07-22 18:15:51

标签: sqlite

我需要为SQLite转换以下表达式,知道如何做到这一点吗?

IF EXISTS (SELECT [ID] FROM [USERS] WHERE [ID]=1)
SELECT [ID], [NAME], [CITY] FROM [USERS] WHERE [ID]=1
ELSE   
SELECT NULL AS ID, NULL AS NAME, NULL AS CITY

UNION ALL

IF EXISTS (SELECT [ID] FROM [USERS] WHERE [ID]=2)
SELECT [ID], [NAME], [CITY] FROM [USERS] WHERE [ID]=2
ELSE   
SELECT NULL AS ID, NULL AS NAME, NULL AS CITY

换句话说,当条件不符合条件时,我需要返回一个带有NULL值的必要列的空行。

2 个答案:

答案 0 :(得分:1)

您可以创建包含所需ID的虚拟表格,然后使用左侧outer join获取匹配的Users记录值或NULL

SELECT Users.*
FROM (SELECT 1 AS ID
      UNION ALL
      SELECT 2) AS IDList
LEFT JOIN Users ON IDList.ID = Users.ID

答案 1 :(得分:0)

SQLite没有IF语句或任何其他控制流语句。

你可以做的是将实际记录(如果存在)一起取出NULL记录,然后只取第一个记录:

SELECT * FROM (SELECT ID, Name, City FROM Users WHERE ID = 1
               UNION ALL
               SELECT NULL, NULL, NULL
               LIMIT 1)
UNION ALL
SELECT * FROM (SELECT ID, Name, City FROM Users WHERE ID = 2
               UNION ALL
               SELECT NULL, NULL, NULL
               LIMIT 1)