我需要的目标是获得最后一次回复来自用户而不是管理员并且最后一次回复是 10 天或更长时间的票。我目前有一个得到最后回复的 SQL,但我很难从管理员那里过滤用户。我当前的 SQL 是:
SELECT
t.tid, tr.reply_date, tr.rid, u.display_name, u.user_type
FROM ticket t
JOIN (
SELECT
tr_last.tid, tr_last.reply_date, tr_last.rid, tr_last.uid
FROM ticket_reply tr_last
ORDER BY tr_last.reply_date DESC
) tr ON tr.tid = t.tid
LEFT JOIN user u ON u.uid = tr.uid
WHERE
t.status != "Closed"
AND DATE_SUB(CURDATE(), INTERVAL 10 DAY) >= tr.reply_date
GROUP BY t.tid;
这会返回类似:
+-------+---------------------+-------+-----------------------------+-----------+
| tid | reply_date | rid | display_name | user_type |
+-------+---------------------+-------+-----------------------------+-----------+
| 6784 | 2012-03-27 04:11:52 | 40061 | (hidden) | admin |
| 8094 | 2013-01-18 21:13:56 | 65037 | (hidden) | admin |
| 8165 | 2012-09-10 14:59:17 | 52956 | (hidden) | admin |
| 8171 | 2012-06-18 19:05:19 | 46527 | (hidden) | user |
| 8313 | 2012-08-16 23:05:51 | 51362 | (hidden) | admin |
| 8436 | 2012-08-16 23:20:20 | 51368 | (hidden) | admin |
| 8453 | 2012-06-26 23:41:37 | 47247 | (hidden) | admin |
| 8712 | 2012-11-22 10:33:05 | 59697 | (hidden) | user |
| 8911 | 2013-09-24 00:52:27 | 89910 | (hidden) | user |
| 8949 | 2013-09-02 16:29:22 | 87718 | (hidden) | user |
+-------+---------------------+-------+-----------------------------+-----------+
如果我u.user_type = "user"
在WHERE
子句中添加,它会更改tr
它检索到的行,因此该6784
tid
行中的用户现在显示用户不是管理员,但该票证的最后回复实际上是管理员。所以这:
SELECT
t.tid, tr.reply_date, tr.rid, u.display_name, u.user_type
FROM ticket t
JOIN (
SELECT
tr_last.tid, tr_last.reply_date, tr_last.rid, tr_last.uid
FROM ticket_reply tr_last
ORDER BY tr_last.reply_date DESC
) tr ON tr.tid = t.tid
LEFT JOIN user u ON u.uid = tr.uid
WHERE
t.status != "Closed"
AND DATE_SUB(CURDATE(), INTERVAL 10 DAY) >= tr.reply_date
AND u.user_type = "user"
GROUP BY t.tid;
现在返回:
+-------+---------------------+-------+-----------------------------+-----------+
| tid | reply_date | rid | display_name | user_type |
+-------+---------------------+-------+-----------------------------+-----------+
| 6784 | 2012-03-26 23:19:52 | 40051 | (hidden) | user |
| 8094 | 2013-01-18 18:53:33 | 65016 | (hidden) | user |
| 8165 | 2012-09-07 01:17:28 | 52831 | (hidden) | user |
| 8171 | 2012-06-18 19:05:19 | 46527 | (hidden) | user |
| 8313 | 2012-08-09 18:37:35 | 50776 | (hidden) | user |
| 8436 | 2012-08-16 23:01:28 | 51359 | (hidden) | user |
| 8453 | 2012-06-21 16:29:24 | 46843 | (hidden) | user |
| 8712 | 2012-11-22 10:33:05 | 59697 | (hidden) | user |
| 8911 | 2013-09-24 00:52:27 | 89910 | (hidden) | user |
| 8949 | 2013-09-02 16:29:22 | 87718 | (hidden) | user |
+-------+---------------------+-------+-----------------------------+-----------+
您可以注意到rid
列值也不同。
所以我的问题是,我如何正确地为此返回用户?