如何获得最新记录

时间:2018-05-07 17:46:31

标签: mysql sql django

我的表格如下:

    let tabBarController : UITabBarController = self.window?.rootViewController as! UITabBarController;
    tabBarController.selectedIndex = 0

    let navigationController  = tabBarController.selectedViewController as! UINavigationController
    let controllers = navigationController.viewControllers // will give array
    if controllers.count > 0 {
        if let viewC = controllers[0] as? DesiredViewController {
       // do desired work
       }
   }

我希望按照以下+--------+-------------+----------+---------+ | PK(id) | FK(user_id) | ctime | comment | +--------+-------------+----------+---------+ | 1 | 1 | 20170101 | "Haha" | +--------+-------------+----------+---------+ | 2 | 2 | 20170102 | "Nope" | +--------+-------------+----------+---------+ | 3 | 2 | 20170104 | "Geez" | +--------+-------------+----------+---------+ | 4 | 1 | 20170110 | "Gone" | +--------+-------------+----------+---------+ 检索最新记录:

FK(user_id)

所以我试过+--------+-------------+----------+---------+ | PK(id) | FK(user_id) | ctime | comment | +--------+-------------+----------+---------+ | 3 | 2 | 20170104 | "Geez" | +--------+-------------+----------+---------+ | 4 | 1 | 20170110 | "Gone" | +--------+-------------+----------+---------+ SELECT DISTINCT T.* FROM my_table AS T; 但是,他们不会工作!

我尝试了GROUP BY语句,如下所示,

SELECT DISTINCT T.user_id FROM my_table AS T

它确实像我期望的那样完美地工作。 所以我开始弄清楚如何将SQL翻译成Django!

首先,我尝试使用RawSQL:

SELECT T.* FROM my_table AS T GROUP BY `user_id` DESC

每当我调用此函数时,Django都会弹出以下错误。

from django.db.models.expressions import RawSQL

def _select_latest_rows(model_class, target_column_name, query_set=None):
    query_set = query_set or model_class.objects
    table_name = model_class._meta.db_table
    raw_sql = '''
    SELECT * FROM %s GROUP BY %s
    '''
    return query_set.annotate(val=RawSQL(raw_sql, (table_name, target_column_name,)))

然后我检查了我的查询字符串:

django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax
blah blah blah...

它返回:

print(_select_latest_rows(model_class, target_column_name, query_set).query)

好吧,我不得不说我对SQL语法并不熟悉,到目前为止,我还没有弄清楚错误存在于此查询字符串中的位置:(

我必须在this answer中建议的模型管理器实例中调用SELECT T.`id`, T.`user_id`, T.`ctime`, T.`comment`, (SELECT * FROM my_table GROUP BY user_id) AS `val` FROM my_table 函数吗?

raw()

或许我不应该在开头使用GROUP BY语句?

2 个答案:

答案 0 :(得分:1)

最简单明了的方法是:

select * 
from my_table t
where ctime = (select max(ctime) from my_table where user_id = t.user_id);

但是,如果limit

多个相同日期,您也可以在内部查询中使用user_id子句
select * 
from my_table t
where id = (select id 
            from my_table 
            where  user_id = t.user_id
            order by ctime desc 
            LIMIT 1);

答案 1 :(得分:0)

的Oracle / PostgreSQL的:

尝试使用以下SQL,它将满足您的要求。

select id,user_id,ctime,comment
from  (select   id,user_id,ctime,comment
                rank() over(partition by user_id order by ctime desc) rn
        from your_table_name
      ) s
where rn = 1;