[英]mysql if count is null then make it zero
How do I set the field most_popular to 0 if its count is null with a select statement inside a select statement 如果在select语句内使用select语句,如果字段count_null为空,如何将most_popular字段设置为0
i've tried IFNULL(SELECT COUNT(*) ...), 0) as most_popular but it won't work and I tried COALESCE(SELECT COUNT(*) ...., 0) as most_popular 我已经尝试过将IFNULL(SELECT COUNT(*)...),0)设置为most_popular,但它无法正常工作,我尝试了将COALESCE(SELECT COUNT(*)....,0)设置为most_popular
$stmt = $db->prepare("SELECT *,
i.medium_image, i.width, i.height,
(SELECT COUNT(*) FROM order_details od WHERE od.product_id = p.product_id) as most_popular
FROM products p
INNER JOIN product_images i on i.product_id = p.product_id
WHERE p.department_id=:department_id AND p.is_active=1
$orderby
LIMIT :limit OFFSET :offset");
Try this, 尝试这个,
SELECT *,
i.medium_image,
i.width,
i.height,
COALESCE(s.totalCount, 0) most_popular
FROM products p
INNER JOIN product_images i
ON i.product_id = p.product_id
LEFT JOIN
(
SELECT product_id, Count(*) totalCount
FROM order_details
GROUP BY product_id
) s ON s.product_id = p.product_id
WHERE p.department_id = :department_id
AND p.is_active = 1
$orderby
LIMIT :limit OFFSET :offset
or how about this, ( your current query ) 或如何处理( 您当前的查询 )
COALESCE((SELECT COUNT(*)
FROM order_details od
WHERE od.product_id = p.product_id), 0) as most_popular
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.