我有一个大数据库,存储了很多关于客户和账单等的信息。我想做的是,使用客户的ID,搜索他们所有的账单,SUM()每个包含的价格,并存储它们以打印一个唯一的账单。所以我沙吞声地想着这个:try { $conn = new PDO('mysql:host=myhost;dbname=accounting','user','pass'); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);}catch(PDOException $e){ echo "ERROR: " . $e->getMessage();}$stmt = $conn->prepare('SELECT GROUP_CONCAT(DISTINCT source_external_subscriber_id) AS ids FROM cdr');$stmt->execute();foreach ($stmt as $row) { $string = $row['ids'];}$array = explode(',', $string);array_pop($array);array_shift($array);$destinationId = 0;foreach ($array as $id) { $stmt2 = $conn->prepare('SELECT id, call_type, source_customer_cost FROM cdr WHERE source_external_subscriber_id = :id AND destination_account_id = :destinationId'); $stmt2->execute(array('id' => $id, 'destinationId' => $destinationId)); foreach ($stmt2 as $row2) { $datos[] = $row2; }}我不相信结果,所以我决定自己检查,首先执行我的代码广告,然后寻找客户将账单数量与数组的长度进行比较(因此还缺少SUM()然后,当我正在寻找一种更有说服力的方式时,我偶然发现了这个非常有用的帖子。所以我把我的代码改成了这个。但在这里,他们只解释如何编写查询,而不是如何将其存储在数组中。try { $conn = new PDO('mysql:host=host;dbname=accounting','user','pass'); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); var_dump($conn);}catch(PDOException $e){ echo "ERROR: " . $e->getMessage();}$destinationId = 0;$stmt2 = $conn->prepare('SELECT source_external_subscriber_id, source_customer_cost FROM cdr WHERE destination_account_id = :destinationId GROUP BY source_external_subscriber_id');$stmt2->execute(array('destinationId' => $destinationId));foreach ($stmt as $row) { $datos[] = $row2;}谢谢大家的帮助,希望大家有美好的一天!
2 回答
慕哥9229398
TA贡献1877条经验 获得超6个赞
因此,如果我正确理解您,则您正在搜索类似以下内容的内容:
SELECT source_external_subscriber_id id, (SELECT SUM(source_customer_cost)) total FROM cdr GROUP BY source_external_subscriber_id;
牛魔王的故事
TA贡献1830条经验 获得超3个赞
因此,这个问题的答案和简单一样棘手:查询返回的数组有重复的行,也许我错了for-each语句,因为我最近开始使用它们。无论如何,以下是查询和我的存储解决方案:
$destinationId = 0;
$stmt2 = $conn->prepare('SELECT source_external_subscriber_id, SUM(source_customer_cost) FROM cdr WHERE destination_account_id = :destinationId GROUP BY source_external_subscriber_id');
$stmt2->execute(array('destinationId' => $destinationId));
foreach ($stmt2 as $row2) {
$data[] = $row2;
}
for ($i=0; $i < sizeof($data); $i++) {
$sanitizedData[$i] = array(
0 => $data[$i][0],
1 => $data[$i][1]
);
}
- 2 回答
- 0 关注
- 110 浏览
添加回答
举报
0/150
提交
取消