如果select_ statement中的select语句的计数为null,如何将字段most_popular设置为0
我尝试过IFNULL(SELECT COUNT(*)...),0)作为most_popular,但它不会工作,我尝试过 COALESCE(SELECT COUNT(*)....,0)as 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");
答案 0 :(得分:3)
试试这个,
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
或者如何,(您当前的查询)
COALESCE((SELECT COUNT(*)
FROM order_details od
WHERE od.product_id = p.product_id), 0) as most_popular