使用SQL查询比较同一个表中的属性

时间:2015-09-07 02:41:56

标签: mysql sql

我有一张内容表,其中的内容如附图所示 enter image description here

有超过100,000个条目。我想获取其中commit = 0的update_date大于commit = 1的update_date的数据。我还需要commit = 1的相应行。 我尝试了一些方法,但需要很长时间才能检索结果。我可以使用的最佳SQL查询是什么。我正在使用MySQL数据库。

修改

我现在更新了表格。有一个名为content_id的属性将行绑定在一起。 像这样的查询给了我想要的一半

select a.* from contents a, contents b where
a.content_id=b.content_id and
a.update_date > b.update_date and
a.committed=0 and b.committed=1

我还希望来自committed = 1的相应条目,但是它们应该作为行附加在底部,而不是作为列垂直连接。

例如,我不能使用

select * from contents a, contents b where
a.content_id=b.content_id and
a.update_date > b.update_date and
a.committed=0 and b.committed=1

因为'b'的结果是垂直附加的。此外,是否有更好的方法来编写此查询。如果数据库中有许多条目,这种方法确实很慢。

1 个答案:

答案 0 :(得分:0)

我假设在上面的例子中,你只需要id = 2和内容id = 1,commit = 0的update_date大于commit = 1的update_date,在这种情况下你需要commited = 1的数据。

我使用的是Oracle,因此您需要在mysql中找到row_number()函数的合适替代品。

逻辑是

  1. 在现有表上创建一个视图以使用rownumber,这样它将按时间顺序给出如下所示的rownumber(看看你是否使用嵌套查询来执行此操作)

         ID, CONTENT_ID, COMMITED, UPDATE_DATE, ROWN
        2   1   1   06-SEP-15 00:00:56  1
        1   1   0   07-SEP-15 00:00:56  2
        3   2   0   03-SEP-15 00:00:56  1
        4   2   1   04-SEP-15 00:00:56  2
    
  2. 现在只选择rown = 1和commited = 1

  3. 的行

    这是oracle中的查询。查询c2的第二个将是您的视图。

    Oracle查询

             with c1 (id, content_id,commited,update_date) as
             (
                 select 1,1,0,sysdate from dual union
                 select 2,1,1,sysdate-1 from dual union
                 select 3,2,0,sysdate-4 from dual union
                 select 4,2,1,sysdate-3 from dual 
             ),
                c2 as 
                (select c1.*,row_number() over(partition by content_id order by update_date) as rown from c1)
                select id,content_id,commited,update_date from c2
                where rown=1 and commited=1
                         ID, CONTENT_ID, COMMITED, UPDATE_DATE, ROWN
    

    输出

             ID, CONTENT_ID, COMMITED, UPDATE_DATE  
                2   1   1   06-SEP-15 00:06:17
    
相关问题