我正在尝试将MySQL表中所有product_id
的所有product_price求和。
当我运行$result = "SELECT SUM(product_price) AS product_price FROM products";
时,它汇总了所有可以正常工作的product_price。
当我运行$result = "SELECT SUM(product_price) AS product_price FROM products WHERE product_id = $school_product_id";
时,它给我一个数组错误。
我希望查询从explode
/ foreach
获取所有4个ID,并显示总价。
正在爆炸的数据库字段看起来像“ 1,2,3,4”,与下面的product_id
表中的products
匹配。
$row = $result->fetch_assoc();
$school_subject_products = $row["school_subject_products"]; // (output is 1,2,3,4)
$school_product_id = explode(',', $school_subject_products); // (explode 1,2,3,4 to use in query below to calculate all 4 product_id's product_price)
$result = "SELECT SUM(product_price) AS product_price FROM products WHERE product_id = ??????????"; //<------ how do I get it to search for all 4 product_ids and total the price of all the product_ids
$price_result = $mysqli->query($result);
$row = $price_result->fetch_assoc();
$sum = $row['product_price'];
echo $sum;
?>
答案 0 :(得分:1)
理想的解决方案是对数据进行规范化处理,这样就没有逗号分隔的列表。
如果无法执行此操作,则可以将JOIN
与FIND_IN_SET()
配合使用,以与逗号分隔的列表进行匹配,而不必执行多个查询并使用explode()
。
SELECT SUM(product_price) AS product_price
FROM products AS p
JOIN select_subject AS s ON FIND_IN_SET(p.product_id, s.school_subject_products)
WHERE school_id = $selected_school_id AND school_year_id = $selected_year_id AND school_subject_id = $school_subject_selected