gpt4 book ai didi

mysql - 在 mySQL WHERE 子句中遇到 IFNULL 问题

转载 作者:行者123 更新时间:2023-11-29 00:01:22 26 4
gpt4 key购买 nike

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

基本上,我试图选择一堆数据来报告向网站提出贷款申请的人,但有两种不同的类型:无抵押和担保。我需要在 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”,否则状态会获胜'存在,因此无抵押贷款的结果将不会显示。希望我解释得足够好!

总而言之,我需要显示所有贷款信息,无抵押和有担保,并使用取反的 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

关于mysql - 在 mySQL WHERE 子句中遇到 IFNULL 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29646758/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com