如何编写复杂的Sqlite SELECT语句?

时间:2011-07-10 02:52:33

标签: sql database sqlite

所以,请允许我举个例子。这就是表格的样子:

+----+------+------+------+
| id | body | date | type |
+----+------+------+------+
| 1  | foo  | 1101 | typ1 |
| 4  | baz  | 1110 | typ1 |
| 3  | bar  | 1115 | typ2 |
| 3  | goo  | 1114 | typ1 |
| 2  | fee  | 1111 | typ2 |
+----+------+------+------+

所以我需要准备一个返回如下内容的SELECT语句:

+----+------+------+------+
| id | body | date | type |
+----+------+------+------+
| 1  | foo  | 1101 | typ1 |
| 3  | goo  | 1114 | typ1 |
| 3  | bar  | 1115 | typ2 | <- this is here because date is greater than 1114
| 4  | baz  | 1110 | typ1 |
| 2  | fee  | 1111 | typ2 | <- this is here because date is greater than 1110
+----+------+------+------+

什么是排序逻辑以及我必须记住的内容?

  • id列实际上不是ID。如您所见,重复了3,区别在于type
  • typ1必须按ID升序排序(在这种情况下date无关紧要。)
  • typ2必须按type1(unix时间)合并到排序date
  • 将句子传递给已经创建的方法(让我们假设它是object.query(“SELECT ... etc.”))。所以我不允许分多步执行此操作。

你有什么想法吗?除了像SELECT ... ORDER BY id ASC这样的基本内容之外,我还没有想到一种解决方法。

修改

这是排序表的构建方式:

  1. 您必须按ID:
  2. 订购typ1

    +----+------+------+------+
    | id | body | date | type |
    +----+------+------+------+
    | 1  | foo  | 1101 | typ1 |
    | 3  | goo  | 1114 | typ1 |
    | 4  | baz  | 1110 | typ1 |
    +----+------+------+------+
    

    然后我们必须按日期排序typ2,但是这个限制:

    • typ2必须出现在不高于typ1 date的较高typ2 date下方。

2 个答案:

答案 0 :(得分:0)

SELECT x.id,x.date, y.body,y.type from table as x left outer join table as y on (x.id=y.id) where x.date >1101 or x.date>1114


我想你想要红色值?我是对的

答案 1 :(得分:0)

我想我明白你的意思。你可以尝试一下,让我知道它是否可以吗?

SELECT
    CASE 
        WHEN type='typ1' THEN id 
        WHEN type='typ2' THEN (
            SELECT T1.id
            FROM TheTable AS T1 
            WHERE T1.date=(SELECT MAX(T2.date)
                           FROM TheTable AS T2
                           WHERE T2.type='typ1' AND T2.date<TheTable.date)
                AND T1.type='typ1')
    END AS order_by_value,
    id, body, date, type
FROM TheTable
ORDER BY order_by_value, type, date;

如果“typ2”记录的日期小于最小的“typ1”日期,则会出现问题;否则它应该可以正常工作。

如果您不想在结果集中使用“order_by_value”列,请以这种方式从上一个SQL查询中进行选择:

SELECT id, body, date, type 
FROM (
SELECT
    CASE 
        WHEN type='typ1' THEN id 
        WHEN type='typ2' THEN (
            SELECT T1.id
            FROM TheTable AS T1 
            WHERE T1.date=(SELECT MAX(T2.date)
                           FROM TheTable AS T2
                           WHERE T2.type='typ1' AND T2.date<TheTable.date)
                AND T1.type='typ1')
    END AS order_by_value,
    id, body, date, type
FROM TheTable
ORDER BY order_by_value, type, date);