0

我收到这样的查询

Select * from tablename where field1 in (a,b,c,d);

我想知道是否有一种方法可以在找不到元素的情况下,dbms 返回该元素的所有字段,并返回 null

例子

+-------+-------+-------+
|field_1|field_2|field_3|
+-------+-------+-------+
|a      |1      |4      |
+-------+-------+-------+
|b      |null   |null   |
+-------+-------+-------+
|c      |4      |5      |
+-------+-------+-------+
4

1 回答 1

0

您没有指定您正在使用什么数据库软件,但您可以创建一个临时表,添加您想要的值,然后左连接到源表:

CREATE TABLE #temp (field1 VARCHAR(10))

INSERT INTO #temp VALUES ('a')
INSERT INTO #temp VALUES ('b')
INSERT INTO #temp VALUES ('c')
INSERT INTO #temp VALUES ('d')

SELECT t1.field1, t2.field2, t2.fields
FROM #temp t1
LEFT JOIN tablename t2 ON t1.field1 = t2.field1

另一种方法是 UNION:

Select * from tablename where field1 in (a,b,c,d)
UNION 
SELECT 'a', null, null, null WHERE 'a' NOT IN (select field1 FROM tablename)
UNION 
SELECT 'b', null, null, null WHERE 'b' NOT IN (select field1 FROM tablename)
UNION 
SELECT 'c', null, null, null WHERE 'c' NOT IN (select field1 FROM tablename)
UNION 
SELECT 'd', null, null, null WHERE 'd' NOT IN (select field1 FROM tablename)

(我假设值'a', 'b', 'c','d'不存在于现有表中 - 否则LEFT JOIN就像临时表示例那样只是该表。)

于 2014-01-20T20:36:08.230 回答