简体   繁体   中英

How can i use IFNULL in Where clause

I want to use IFNULL() in such a way that I can select the record containing NULL or, if a value is present, then select the record matchinga particular value.

My query is:

SELECT (@v:=2) AS Row, CL.LeaveTypeId, CL.NumberOfLeave
FROM `CompanyLeave` CL
WHERE(IFNULL(CL.EmploymentType,0)=3);

column EmploymentType can contain either an Integer or NULL .

I want to select the record matching the specified value, or, if none matches, then the record containing NULL .

I am interpreting the question as a prioritization. If a record with 3 exists, choose that. Otherwise, choose the one that is NULL , if it exists.

If so, this might do what you want:

SELECT (@v:=2) AS Row, CL.LeaveTypeId, CL.NumberOfLeave
FROM `CompanyLeave` CL
WHERE CL.EmployementType = 3 or CL.EmployementType IS NULL
ORDER BY (CL.EmployementType = 3) DESC
LIMIT 1;

This will return the row with 3 , if present. Otherwise, it will return a row with NULL , if one exists.

The expression IFNULL(CL.EmploymentType, 3) basically means: if CL.EmploymentType IS NULL then use 3 instead. The original value of CL.EmploymentType is used if it is not NULL .

If I understand correctly your question, you need to select the rows having NULL or 3 in the column CL.EmploymentType .
The query is:

SELECT (@v:=2) AS Row, CL.LeaveTypeId, CL.NumberOfLeave
FROM `CompanyLeave` CL
WHERE IFNULL(CL.EmploymentType, 3) = 3;

Update:

If only one row must be returned (the one having 3 being preferred over those having NULL ) then the rows must be sorted using a criteria that puts the NOT NULL value in front and a LIMIT 1 clause must be added.

MySQL documentation about NULL says:

When doing an ORDER BY , NULL values are presented first if you do ORDER BY ... ASC and last if you do ORDER BY ... DESC .

The updated query is:

SELECT (@v:=2) AS Row, CL.LeaveTypeId, CL.NumberOfLeave
FROM `CompanyLeave` CL
WHERE IFNULL(CL.EmploymentType, 3) = 3;
ORDER BY CL.EmploymentType DESC
LIMIT 1

You can use IF statement instead of IFNULL()

IF(condition, expres1, expres2) 

It means that if condition is satisfied then return expres1 else expres2

SELECT (@v:=2) AS Row, CL.LeaveTypeId, CL.NumberOfLeave
FROM `CompanyLeave` CL
WHERE IF(CL.EmploymentType IS NULL, 0, CL.EmploymentType) = 3;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM