我的php脚本中有一个MySQL查询,目前工作正常。我唯一的问题是有些列返回空值。
如果这些列有数据,则它们返回值,但如果没有数据或日期记录,则返回null。我想要做的就是修改这个查询,这样如果有什么是null,它就会返回' 0'。
我不确定是否应该使用IFNULL或合并,但无论如何我不熟悉将此方法应用于此查询的最佳方式。
非常感谢任何帮助。
$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;
答案 0 :(得分:0)
是的,您可以使用IFNULL。但是要确定你真的想要这种行为。 PHP也熟悉NULL值,可以很好地处理它们。 0具有非常不同的含义。但是如果你确实想要这种行为,只需在IFNULL中包装可能返回null的字段或语句,例如:
SELECT IFNULL(user_id, 0);
但您也可以在PHP本身中执行此操作,因此您无需修改查询:
if (is_null($result['field'])) {
echo 0;
}
或者,如果您使用PHP 7+,您还可以使用null coalescing operator:
echo $result['field'] ?? 0;