返回具有特定条件的所有行

时间:2013-07-16 16:48:24

标签: mysql sql

首先让我告诉你们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

我正在尝试构建的查询应该返回所有行,如果to_user_id = $ user_id并且to_delete有值或者如果from_user_id = $ user_id并且from_delete已经一个值,按thread_hash分组(即您从收件箱或发件箱中删除的主题)

我希望我在这里清楚。如果我能清除其他任何内容,请告诉我。

1 个答案:

答案 0 :(得分:1)

你很接近,一个简单的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;

The modified SQLfiddle for testing