NULL 또는 IS NULL이있는 IN 절
Postgres는 데이터베이스입니다.
IN 절에 NULL 값을 사용할 수 있습니까? 예:
SELECT *
FROM tbl_name
WHERE id_field IN ('value1', 'value2', 'value3', NULL)
이 네 가지 값으로 제한하고 싶습니다.
위의 문을 시도했지만 작동하지 않습니다. 잘 실행되지만 NULL id_fields가있는 레코드를 추가하지 않습니다.
나는 또한 OR 조건을 추가하려고 시도했지만 이것은 쿼리를 실행하고 끝없이 실행합니다.
SELECT *
FROM tbl_name
WHERE other_condition = bar
AND another_condition = foo
AND id_field IN ('value1', 'value2', 'value3')
OR id_field IS NULL
어떤 제안?
in
문은 동일하게 해석됩니다field=val1 or field=val2 or field=val3
. 거기에 null을 넣으면field=null
작동하지 않을 것입니다.
나는 명확성을 위해 이것을 할 것입니다
SELECT *
FROM tbl_name
WHERE
(id_field IN ('value1', 'value2', 'value3') OR id_field IS NULL)
연산자 우선 순위 로 인해 쿼리가 실패합니다 . AND
전에 바인딩합니다 OR
!
"명확성"의 문제가 아니라 순수한 논리 필요성 의 문제인 한 쌍의 괄호가 필요 합니다.
SELECT *
FROM tbl_name
WHERE other_condition = bar
AND another_condition = foo
AND (id_field IN ('value1', 'value2', 'value3') OR id_field IS NULL)
추가 된 괄호는 AND
앞에 바인딩을 방지 OR
합니다. 다른 WHERE
조건 (아니오 AND
)이 없으면 괄호 가 필요 하지 않습니다 . 이 점에서 받아 들여지는 대답은 약간 오해의 소지가 있습니다.
SELECT *
FROM tbl_name
WHERE coalesce(id_field,'unik_null_value')
IN ('value1', 'value2', 'value3', 'unik_null_value')
그래서 당신은 검사에서 널을 제거합니다. id_field에 null 값이 주어지면 coalesce 함수는 null 대신 'unik_null_value'를 반환하고 IN-list에 'unik_null_value를 추가하여 쿼리는 id_field가 value1-3 또는 null 인 게시물을 반환합니다.
Daniel이 대답 한 질문은 매우 훌륭합니다. NULLS에 관한 메모를 남기고 싶었습니다. 열에 NULL 값이 포함 된 경우 NOT IN 연산자를 사용할 때주의해야합니다. 열에 NULL 값이 포함되어 있고 NOT IN 연산자를 사용하는 경우 출력이 표시되지 않습니다. 이것이 여기 http://www.oraclebin.com/2013/01/beware-of-nulls.html 에서 설명하는 방법입니다.이 글은 제가 만나서 공유 할 생각이었던 아주 좋은 기사입니다.
참고 : 누군가 Sushant Butta의 답변 에서 외부 링크가 죽었다고 주장했기 때문에 여기에 별도의 답변으로 콘텐츠를 게시했습니다.
NULLS에 주의하십시오 .
오늘 저는 IN과 NOT IN
연산자 를 사용하는 동안 매우 이상한 쿼리 동작을 발견했습니다 . 실제로 두 테이블을 비교하고 값이 table b
존재 하는지 여부를 table a
확인하고 열에 null
값이 포함 된 경우 동작을 확인하고 싶었습니다 . 그래서 방금이 동작을 테스트하기위한 환경을 만들었습니다.
테이블을 생성합니다 table_a
.
SQL> create table table_a ( a number);
Table created.
테이블을 생성합니다 table_b
.
SQL> create table table_b ( b number);
Table created.
에 일부 값을 삽입하십시오 table_a
.
SQL> insert into table_a values (1);
1 row created.
SQL> insert into table_a values (2);
1 row created.
SQL> insert into table_a values (3);
1 row created.
에 일부 값을 삽입하십시오 table_b
.
SQL> insert into table_b values(4);
1 row created.
SQL> insert into table_b values(3);
1 row created.
이제 연산자 table_a
를 table_b
사용하여 값을 확인하여 값 의 존재를 확인하는 쿼리를 실행합니다 IN
.
SQL> select * from table_a where a in (select * from table_b);
A
----------
3
아래 쿼리를 실행하여 존재하지 않는지 확인하십시오.
SQL> select * from table_a where a not in (select * from table_b);
A
----------
1
2
출력이 예상대로 나왔습니다. 이제 null
테이블에 값을 삽입 table_b
하고 위의 두 쿼리가 어떻게 작동하는지 살펴 보겠습니다.
SQL> insert into table_b values(null);
1 row created.
SQL> select * from table_a where a in (select * from table_b);
A
----------
3
SQL> select * from table_a where a not in (select * from table_b);
no rows selected
The first query behaved as expected but what happened to the second query? Why didn't we get any output, what should have happened? Is there any difference in the query? No.
The change is in the data of table table_b
. We have introduced a null
value in the table. But how come it's behaving like this? Let's split the two queries into "AND"
and "OR"
operator.
First Query:
The first query will be handled internally something like this. So a null
will not create a problem here as my first two operands will either evaluate to true
or false
. But my third operand a = null
will neither evaluate to true
nor false
. It will evaluate to null
only.
select * from table_a whara a = 3 or a = 4 or a = null;
a = 3 is either true or false
a = 4 is either true or false
a = null is null
Second Query:
The second query will be handled as below. Since we are using an "AND"
operator and anything other than true
in any of the operand will not give me any output.
select * from table_a whara a <> 3 and a <> 4 and a <> null;
a <> 3 is either true or false
a <> 4 is either true or false
a <> null is null
So how do we handle this? We will pick all the not null
values from table table_b
while using NOT IN
operator.
SQL> select * from table_a where a not in (select * from table_b where b is not null);
A
----------
1
2
So always be careful about NULL
values in the column while using NOT IN
operator.
Beware of NULL!!
I know that is late to answer but could be useful for someone else You can use sub-query and convert the null to 0
SELECT *
FROM (SELECT CASE WHEN id_field IS NULL
THEN 0
ELSE id_field
END AS id_field
FROM tbl_name) AS tbl
WHERE tbl.id_field IN ('value1', 'value2', 'value3', 0)
참고URL : https://stackoverflow.com/questions/6362112/in-clause-with-null-or-is-null
'Programing' 카테고리의 다른 글
파일 경로에서 환경 변수 사용 (0) | 2020.11.08 |
---|---|
왜 우리는 들쭉날쭉 한 배열과 다차원 배열을 가지고 있습니까? (0) | 2020.11.08 |
최신 Java와 배열 목록의 동일성을 비교하는 방법은 무엇입니까? (0) | 2020.11.08 |
OpenSSL 라이브러리를 사용하여 C ++에서 SHA 해시 생성 (0) | 2020.11.08 |
postgresql의 Rownum (0) | 2020.11.08 |