gpt4 book ai didi

php - mysql如果计数为空则将其设为零

转载 作者:太空宇宙 更新时间:2023-11-03 12:29:06 24 4
gpt4 key购买 nike

如果在 select 语句中使用 select 语句,如果字段 most_popular 的计数为空,我如何将其设置为 0

我试过 IFNULL(SELECT COUNT(*) ...), 0) 作为 most_popular 但它不起作用,我试过了COALESCE(SELECT COUNT(*) ...., 0) 最流行

    $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");

最佳答案

试试这个,

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

关于php - mysql如果计数为空则将其设为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16291654/

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