這個問題在這里已經有了答案: 在多列上使用 group by (3 個回答) MySQL 結果作為逗號分隔串列 (4 個答案) MySQL 將某些結果分組到一個陣列中 1 個回答 4 小時前關閉。
SQL 表 [訂單]
| orderId | dueDate | emailAddress |
| ------- | ---------- | -------------- |
| 1010101 | 10/11/2021 | joe@gmail.com |
| 1010102 | 10/11/2021 | joe@gmail.com |
| 1010103 | 10/11/2021 | joe@gmail.com |
| 1010104 | 10/11/2021 | john@gmail.com |
| 1010105 | 10/11/2021 | john@gmail.com |
| 1010106 | 10/11/2021 | john@gmail.com |
PHP腳本
$query = "SELECT * FROM orders";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
$order = $row['orderId'];
$to = $row['emailAddress'];
$sub = "Payment Due Reminder";
$body = "Due reminder message with order ID $order";
mail($to, $sub, $body);
}
我的要求
現在我只想發送一封列出三個訂單 ID 的電子郵件,而不是向同一個收件人發送三封電子郵件。有沒有辦法實作它?
uj5u.com熱心網友回復:
我將使用聚合查詢在 MySQL 中處理此問題:
$query = "SELECT dueDate, emailAddress, GROUP_CONCAT(orderId) AS all_orders
FROM orders
GROUP BY dueDate, emailAddress";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
$all_orders = $row['all_orders'];
$to = $row['emailAddress'];
$sub = "Payment Due Reminder";
$body = "Due reminder message with order ID $all_orders";
mail($to, $sub, $body);
}
uj5u.com熱心網友回復:
為什么表中有重復資料?
<?php
$query = "SELECT * FROM orders";
$result = mysqli_query($conn, $query);
$sentList = [];
while ($row = mysqli_fetch_assoc($result)) {
if (key_exists($row['emailAddress'], $sentList)) {
continue;
}
$order = $row['orderId'];
$to = $row['emailAddress'];
$sub = "Payment Due Reminder";
$body = "Due reminder message with order ID $order";
mail($to, $sub, $body);
$sentList[$to] = 1;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/355537.html
上一篇:插入到使用資料庫上的默認值
