1

我需要为 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 值的必要列。

4

2 回答 2

1

您可以创建一个包含所有所需 ID 的虚拟表,然后使用左外连接来获取匹配的Users记录值或NULL

SELECT Users.*
FROM (SELECT 1 AS ID
      UNION ALL
      SELECT 2) AS IDList
LEFT JOIN Users ON IDList.ID = Users.ID
于 2013-07-22T20:04:08.960 回答
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)
于 2013-07-22T19:58:00.607 回答