IFNULL()&&COALESCE()

    In MySQL, IFNULL() functions are available, but note that they cannot be used directly on the results of aggregate functions. To return a specific value in cases where the result of an aggregate function might be NULL, you should use  COALESCE() a function instead of  IFNULL() a function.

Here is a code example:

COALESCE(SUM(pc.CONTRACT_TOTAL), 0) AS yearPayment

        The code above compares the result of SUM(pc.CONTRACT_TOTAL) to 0 and returns a non-null result. This will return 0 even if the result is NULL.

        For aggregate functions, replace  COALESCE() the previous function with a function  IFNULL() . In this way, the "Incorrect parameters in the call to native function 'ifnull'" error will no longer appear when executing the query.

        Of course, there is another situation, that is, when using window functions, the example is as follows:

        MySQL 8.0 and above support the use of window functions. Window functions allow a value to be calculated for each row in the query results and can be used in conjunction with other aggregate functions such as SUM, COUNT, etc. Window functions use the OVER clause to define the window range.

        An example SUM(INVOICE_AMOUNT) OVER (PARTITION BY PROJECT_ID, CONTRACT_ID) is an expression that uses a window function to perform a sum calculation. It partitions the data based on  PROJECT_ID the  CONTRACT_ID sum and calculates  INVOICE_AMOUNT the sum of the fields for each partition. Then use  IFNULL() the function to compare the result of the window function's evaluation to 0 and return 0 if the result is NULL. IFNULL() Function used to determine whether the result of a window function is NULL, providing a default value if required.

        The reason a function can be used here  IFNULL() is because the calculation of the window function is performed on the result set of the SELECT query, rather than being applied to the result of the aggregate function. General aggregate functions (such as SUM, COUNT) can be used  IFNULL(), but window functions do not need to be handled this way, because they will directly calculate and return a non-empty result.

        It should be noted here that in different database systems, the syntax and support of window functions may be different. Make sure that the database system you use supports window functions, and understand the window function syntax and usage of the corresponding database.

Guess you like

Origin blog.csdn.net/friggly/article/details/131943467