在 mySQL WHERE 子句中遇到 IFNULL 问题

Having trouble with an IFNULL in a mySQL WHERE clause

在任何人说之前,我已经为我的问题搜索了合适的答案,但找不到足够具体的答案,所以我想问一下。

基本上,我正在尝试 select 一堆数据,用于向网站提出贷款申请的人的报告,但有两种不同的类型:无担保和担保。我需要在 WHERE 子句中放置一个 IFNULL 语句,以便我仅在某个其他字段不为空时才使用该子句。

这是我的声明:

SELECT 
    la.`lms_loan_application_id`,
    la.`created`,
    la.`updated`,
    la.`loan_amount`,
    la.`loan_term`,
    la.`loan_document_fee`,
    la.`broker_reference`,
    la.`broker_sub_reference`,
    laa.`first_name`,
    laa.`surname`,
    laa.`dob`,
    laa.`email`,
    laa.`mobile_number`,
    laaAd.`address_postcode`,
    lag.`first_name`,
    lag.`surname`,
    lag.`dob`,
    lag.`email`,
    lag.`mobile_number`,
    lagAd.`address_postcode`,
    lagAd.`housing_status`
FROM
    loan_application AS la
        JOIN
    loan_application_applicant AS laa ON la.`id` = laa.`loan_application`
        LEFT JOIN
    loan_application_guarantor AS lag ON la.`id` = lag.`loan_application`
        JOIN
    loan_application_address AS laaAd ON laaAd.`loan_application_applicant` = laa.`id`
        LEFT JOIN
    loan_application_address AS lagAd ON lagAd.`loan_application_guarantor` = lag.`id`
WHERE
    la.`status` = 'signature_given'
        AND ! IFNULL(lag.`first_name`,
            lag.`status` = 'signature_given')
        AND laa.`status` = 'signature_given'
        AND ! IFNULL(lag.`first_name`,
            lagAd.`current_address` = 1)
        AND laaAd.`current_address` = 1
ORDER BY la.`updated` DESC
LIMIT 10000

如您所见,我已尝试使用 IFNULL(尽管以一种否定的方式,但我认为这行得通吗?)但我得到的只是重复的行结果,而不是我真正想要的结果集。

基本上,只有当 lag.first_name 字段不为空(即有担保人姓名)时,我才需要使用 where 子句 "lag.status = 'signature_given" 和 "lagAd.current_address = 1",否则状态将不会' t 存在,因此不会显示无抵押贷款的结果。希望我解释得足够好!

总而言之,我需要显示所有贷款信息,无抵押和有担保,并使用取反的 IFNULL 以确定何时考虑 WHERE 子句。

感谢任何帮助!

提前致谢 迈克尔

来自this MySQLTutorial article

Notice that you should avoid using the IFNULL function in the WHERE clause, because it degrades the performance of the query. If you want to check if a value is NULL or not, you can use IS NULL or IS NOT NULL in the WHERE clause.

这是一个 WHERE 子句,它使用 IS NULLIS NOT NULL 而不是 IFNULL 来正确实现您的逻辑:

WHERE la.`status` = 'signature_given' AND
(lag.`first_name` IS NULL OR
(lag.`first_name` IS NOT NULL AND lag.`status` = 'signature_given')) AND
laa.`status` = 'signature_given' AND
(lag.`first_name` IS NULL OR
(lag.`first_name` IS NOT NULL AND lagAd.`current_address` = 1)) AND 
laaAd.`current_address` = 1