mysql not in子查詢返回結果為空
今天寫sql語句的時候,希望通過not in子查詢來限制查詢結果,實際SQL語句如下:
select ID as id, TYPE_CODE as typeCode , TYPE_NAME as typeName ,
PARENT_ID as parentsId , STYLE as style , LEVELS as levels
from type_code
where PARENT_ID = '30119a0e-2f57-473d-9f1d-2843561e9064' and ID not in
( select PARENT_ID from type_code where PARENT_ID);
結果滿足查詢的條件為空……
後來發現,子查詢中存在欄位的某些值為null,所以導致了count=0.
所以,將SQL調整為如下:
select ID as id, TYPE_CODE as typeCode , TYPE_NAME as typeName ,
PARENT_ID as parentsId , STYLE as style , LEVELS as levels
from type_code
where PARENT_ID = '30119a0e-2f57-473d-9f1d-2843561e9064' and ID not in
( select PARENT_ID from type_code where PARENT_ID is not null);
這樣就能正確的查出結果了!
總結:MySQL中如果要用not in在子查詢中限制結果,那必須要將子查詢的結果集限制為不含null,不然查詢結果count = 0.