SQLite foreach类型的行

时间:2014-03-31 18:37:36

标签: php sql database sqlite

我有桌子例如

+------+--------+--------+---------------------+
| Type | Value1 | Value2 |      DateAdded      |
+------+--------+--------+---------------------+
|    1 | a      | a      | 2014-03-31 20:00:00 |
|    2 | a      | a      | 2014-03-31 20:00:10 |
|    3 | a      | a      | 2014-03-31 20:00:25 |
|    1 | a      | a      | 2014-03-31 20:00:40 |
|    2 | a      | a      | 2014-03-31 20:00:50 |
|    3 | a      | a      | 2014-03-31 20:00:60 |
|    1 | a      | a      | 2014-03-31 20:01:10 |
|    2 | a      | a      | 2014-03-31 20:01:25 |
|    3 | a      | a      | 2014-03-31 20:01:35 |
+------+--------+--------+---------------------+

还有更多行...我想在一个查询中收到:

  • 20行WHERE type = 1 ORDER BY DateAdded DESC
  • 20行WHERE type = 2 ORDER BY DateAdded DESC
  • 20行WHERE type = 3 ORDER BY DateAdded DESC

并且可以有三种以上的类型。

1 个答案:

答案 0 :(得分:1)

此类查询的一种方法是子查询方法中的count(*)

select *
from table t
where 20 >= (select count(*)
             from table t2
             where t2.type = t.type and
                   t2.DateAdded >= t.DateAdded
            );

计算具有较大DateAdded的相同时间的行数,并选择最多包含20个的行。