首先,让我给大家介绍一下SQLFiddle:http://sqlfiddle.com/#!2 / 1d8bd / 11
我已经为此工作了一段时间,并且正面临着一些程序员(和作家)的阻挠。
这是我试图在MySQL中完成的示例伪代码:
Return all rows WHERE { IF `to_user_id` = '27' AND `to_delete` >= SUBDATE(NOW(), INTERVAL 720 HOUR) RETURN to_delete as del_time, COUNT(*), MAX(subject), - OR - IF `from_user_id` = '27' AND `from_delete` >= SUBDATE(NOW(), INTERVAL 720 HOUR) ) RETURN from_delete as del_time, COUNT(*), MAX(subject), } GROUP BY thread_hash
我实质上是在构建一个私人消息传递系统,这是代表垃圾箱的查询。具有相同行的行thread_hash表示线程中的消息。当用户从其收件箱中删除线程时,它会将所有线程都to_delete设置NOW()为该特定线程thread_hash。当用户从其发件箱中删除线程时,该线程将所有from_delete设置NOW()为thread_hash。
thread_hash
to_delete
NOW()
from_delete
我尝试构建的查询应返回所有行,如果to_user_id= $ user_id且 to_delete具有值,或者如果from_user_id= $ user_id且 from_delete具有值,则按thread_hash (即从您的收件箱或发件箱中删除的线程)分组
to_user_id
from_user_id
我希望我在这里很清楚。请让我知道是否可以清除其他任何内容。
你很亲密,一个简单的就UNION ALL可以做你想要的;
UNION ALL
SELECT MAX(del_time), COUNT(*) cnt, MAX(subject) subject FROM ( SELECT to_delete del_time, thread_hash, subject FROM messages WHERE to_user_id = 27 AND `to_delete` >= SUBDATE(NOW(), INTERVAL 720 HOUR) UNION ALL SELECT from_delete del_time, thread_hash, subject FROM messages WHERE from_user_id = 27 AND `from_delete` >= SUBDATE(NOW(), INTERVAL 720 HOUR) ) a GROUP BY thread_hash;
修改后的SQLfiddle用于测试。