2013-09-01 54 views
0

我有一個分配給多個用戶的任務列表。我想設置一個cron作業並每小時向每個用戶發送一次電子郵件通知。這裏是我的查詢:PHP:通過電子郵件連接數據庫結果

SELECT t.*, u.name, u.email 
FROM tasks t, users u 
WHERE t.date_created > DATE_SUB(NOW(), INTERVAL 1 HOUR) AND t.user_id = u.id 
ORDER BY t.date_created ASC 

下面是結果(我修剪幾列,以更好地適應):

+----+-------+---------------------+---------+--------+------+--------------+ 
| id | title |  date_created | user_id | status | name |  email | 
+----+-------+---------------------+---------+--------+------+--------------+ 
| 9 | task1 | 2013-09-01 17:56:10 | 2 | active | John | [email protected] | 
| 10 | task2 | 2013-09-01 17:57:20 | 1 | active | Tim | [email protected] | 
| 11 | task3 | 2013-09-01 17:58:30 | 2 | active | John | [email protected] | 
| 12 | task4 | 2013-09-01 17:59:40 | 1 | active | Tim | [email protected] | 
+----+-------+---------------------+---------+--------+------+--------------+ 

的問題是,我無法弄清楚如何連接屬於一個任務某些user_id,然後將它們發送到指定的電子郵件。因此,對於上面的例子中,將有兩個電子郵件發出:

  1. TASK1和任務3(以[email protected]
  2. TASK2和任務4(以[email protected]
+0

我不知道你問什麼,但嘗試'GROUP BY email'或'GROUP BY user_id'? – putvande

回答

3

嘗試用GROUP_CONCAT aggregate命令:

SELECT GROUP_CONCAT(t.title), u.name, u.email 
FROM tasks t, users u 
WHERE t.date_created > DATE_SUB(NOW(), INTERVAL 1 HOUR) AND t.user_id = u.id 
GROUP BY u.id 

這將輸出類似:

task1,task3 | John | [email protected] 
task2,task4 | Tim | [email protected] 

默認是逗號分隔的字符串,但您可以指定其他分隔是這樣的:GROUP_CONCAT(t.title,' and ')

+0

謝謝!您還可以使用'SELECT GROUP_CONCAT(t.title)作爲標題'來更改列標題。 – Norbert