知道sql中IN子句中不存在哪些元素

时间:2014-01-20 20:27:05

标签: sql db2 sql-in

我收到了像这样的查询

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      |
+-------+-------+-------+

1 个答案:

答案 0 :(得分: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像临时表一样的表。)