我有一张这样的表:
// mytable
+----+-----------------+
| id | timestamp |
+----+-----------------+
| 1 | 1452001861 | -- yesterday
| 2 | 1452088272 | -- today
| 3 | 1452088283 | -- today
| 4 | 1451915461 | -- last week
| 5 | 1452001861 | -- yesterday
| 6 | 1452088263 | -- today
| 7 | 1252388263 | -- out of {today, yesterday, last week}
| 8 | 1452088312 | -- today
| 9 | 1452001762 | -- yesterday
| 10 | 1222388263 | -- out of {today, yesterday, last week}
| 12 | 1451915459 | -- last week
+----+-----------------+
这是我的疑问:
SELECT * FROM mytable
WHERE DATE(FROM_UNIXTIME(timestamp)) >= CURDATE() - INTERVAL 7 DAY
ORDER BY timestamp DESC
上面的查询选择所有行,从现在到最后7天。
现在有时所有行都在前7天之前(我的意思是最新的行例如在最后8天添加)然后该查询的输出将是空的(选择0行) 。
我想要的是,如果没有选择行(0行),则选择5个最后一行(之前已添加)。我怎么能这样做?
答案 0 :(得分:2)
您可以尝试这种方法:
SET @row_count := (SELECT COUNT(*)
FROM mytable
WHERE DATE(FROM_UNIXTIME(timestamp)) >= CURDATE() - INTERVAL 7 DAY);
IF (@row_count > 0) THEN
SELECT *
FROM mytable
WHERE DATE(FROM_UNIXTIME(timestamp)) >= CURDATE() - INTERVAL 7 DAY
ORDER BY timestamp DESC;
ELSE
SELECT *
FROM mytable
ORDER BY timestamp DESC
LIMIT 5;
END IF;