我正在运行查询表,以查找缺少的值,请参见下面的示例。我想要一个返回匹配行以及不匹配行的查询。
select first, last, id
from sometable
where id not in (1234, 5678, 918, 123, 345, 567, 789, 901, 111, 222, 333, 444)
+----------+---------+---------+
| Returned | | |
+----------+---------+---------+
| FIRST | LAST | ID |
| Fir | Las | 123 |
| Sand | Mud | 222 |
| Stud | Wood | 345 |
| Nail | Metal | 444 |
| Fiber | Glass | 567 |
| Max | Money | 789 |
| Less | Piece | 5678 |
+----------+---------+---------+
+----------+-------+------+
| Expected | | |
+----------+-------+------+
| FIRST | LAST | ID |
| Fir | Las | 123 |
| Sand | Mud | 222 |
| Stud | Wood | 345 |
| Nail | Metal | 444 |
| Fiber | Glass | 567 |
| Max | Money | 789 |
| Less | Piece | 5678 |
| | | 1234 |
| | | 918 |
| | | 901 |
| | | 111 |
| | | 333 |
+----------+-------+------+
答案 0 :(得分:2)
您将需要这样的东西
select t.id,s.first,s.last
from
(SELECT regexp_substr(txt, '[^,]+', 1, LEVEL) id
FROM
(SELECT
'1234, 5678, 918, 123, 345, 567, 789, 901, 111, 222, 333, 444' AS txt
-- Put your in clause above without new line.
FROM dual
)
CONNECT BY regexp_substr(txt, '[^,]+', 1, LEVEL) IS NOT NULL
) t
left join
sometable s
on t.id=s.id
输出
+------+--------+--------+
| ID | FIRST | LAST |
+------+--------+--------+
| 123 | Fir | Las |
| 222 | Sand | Mud |
| 345 | Stud | Wood |
| 444 | Nail | Metal |
| 567 | Fiber | Glass |
| 789 | Max | Money |
| 5678 | Less | Piece |
| 111 | (null) | (null) |
| 1234 | (null) | (null) |
| 918 | (null) | (null) |
| 901 | (null) | (null) |
| 333 | (null) | (null) |
+------+--------+--------+
答案 1 :(得分:0)
您可能将无法执行此操作,因为您只会收到一列数据,而不是整个结果集。
检查表列是否允许空值,如果允许,则可以通过简单插入添加异常值(1234、5678、918、123、345、567、789、901、111、222、333、444)在查询末尾。
答案 2 :(得分:0)
如果我完全理解你,这也许行得通,但是添加你想要和你不想要的条件
Select id, first,last from sometable
Where id in ('123','222','345')
Union
Select null, null, last from sometable
Where id in ('345','444')
答案 3 :(得分:0)
另一个选择:将您感兴趣的id放入临时表中,并进行外部联接:
(Sqlite语法;根据Oracle的需要进行调整)
CREATE TABLE sometable(id INTEGER PRIMARY KEY, first TEXT, last TEXT);
-- Populate sometable
CREATE TEMPORARY TABLE temptable(id INTEGER PRIMARY KEY);
INSERT INTO temptable VALUES (1234), (5678), (918), (123), (345), (567), (789),
(901), (111), (222), (333), (444);
SELECT first, last, t.id AS id
FROM temptable AS t
LEFT OUTER JOIN
sometable AS s
ON s.id = t.id;
产生
first last id
---------- ---------- ----------
111
Fir Las 123
Sand Mud 222
333
Stud Wood 345
Nail Metal 444
Fiber Glass 567
Max Money 789
901
918
1234
Less Piece 5678
编辑:如果需要,您也可以使用CTE来保存值,而不是临时表。