我的php脚本中有一个mysql查询,目前运行良好。唯一的问题是有些列返回空值。
如果有这些列的数据,则返回值,但如果没有日期的数据或记录,则返回null。我所要做的就是修改这个查询,以便如果有任何内容为null,它将返回“0”。
我不确定是否应该使用ifnull或coalesce,但无论哪种方法,我都不熟悉将其应用于此查询的最佳方法。
非常感谢您的帮助。
$stmt3 = mysqli_prepare($conn2,
"UPDATE ambition.ambition_totals a
INNER JOIN
(SELECT
c.user AS UserID,
COUNT(*) AS dealers,
ROUND((al.NumberOfDealers / al.NumberOfDealerContacts) * 100 ,2) AS percent
FROM jfi_dealers.contact_events c
JOIN jackson_id.users u
ON c.user = u.id
JOIN jfi_dealers.dealers d
ON c.dealer_num = d.dealer_num
LEFT JOIN (
SELECT user_id, COUNT(*) AS NumberOfDealerContacts,
SUM(CASE WHEN ( d.next_call_date + INTERVAL 7 DAY) THEN 1 ELSE 0 END) AS NumberOfDealers
FROM jackson_id.attr_list AS al
JOIN jfi_dealers.dealers AS d ON d.csr = al.data
WHERE al.attr_id = 14
GROUP BY user_id) AS al
ON al.user_id = c.user
GROUP BY UserID) as cu
on cu.UserID = a.ext_id
SET a.dealers_contacted = cu.dealers,
a.percent_up_to_date = cu.percent;
") or die(mysqli_error($conn2));
更新
带有ifnull语句的版本:
UPDATE ambition.ambition_totals a
INNER JOIN
(SELECT
c.user AS UserID,
ifnull(count(*),0) AS dealers,
ifnull(ROUND((al.NumberOfDealers / al.NumberOfDealerContacts) * 100 ,2),0) AS percent
FROM jfi_dealers.contact_events c
JOIN jackson_id.users u
ON c.user = u.id
JOIN jfi_dealers.dealers d
ON c.dealer_num = d.dealer_num
LEFT JOIN (
SELECT user_id, COUNT(*) AS NumberOfDealerContacts,
SUM(CASE WHEN ( d.next_call_date + INTERVAL 7 DAY) THEN 1 ELSE 0 END) AS NumberOfDealers
FROM jackson_id.attr_list AS al
JOIN jfi_dealers.dealers AS d ON d.csr = al.data
WHERE al.attr_id = 14
GROUP BY user_id) AS al
ON al.user_id = c.user
WHERE c.created_at >= CURDATE()
GROUP BY UserID) as cu
on cu.UserID = a.ext_id
SET a.dealers_contacted = cu.dealers,
a.percent_up_to_date = cu.percent;
1条答案
按热度按时间hgb9j2n61#
是的,可以使用ifnull。但要确保你真的想要这种行为。php也熟悉空值,可以很好地处理它们。0具有完全不同的含义。但是,如果确实需要这种行为,只需在ifnull中 Package 可能返回null的字段或语句,例如:
但您也可以在php本身中执行此操作,因此不必修改查询:
或者,如果使用PHP7+,也可以使用空合并运算符: