分类 "SQLAlchemy" 下的文章

问题:使用sqlalchemy如何随机获取数据?

解决:使用self.db.execute解析原生sql

方法:

user = self.db.execute(
    """SELECT * FROM users AS t1 JOIN(
        SELECT ROUND(
            RAND() * ((SELECT MAX(id) FROM users)-(SELECT MIN(id) FROM users))
            +(SELECT MIN(id) FROM users)
            ) AS rid
        ) AS t2
WHERE t1.id >= t2.rid
ORDER BY t1.id LIMIT 1;""").fetchone()
注:只能产生一条随机数据,产生多条时可使用fechall(),但是是顺序下去的

products = self.db.execute(
    "select id from products order by rand() limit 10;").fetchall()
这种方法是可以产生多条数据的
考虑到此方法效率不高,建议使用循环调用方法一

参考:

http://www.mantutu.com/index.php/mysql/271.html

问题:sqlalchemy使用中,如何更新数据库数据

方法:
一、使用update方法

self.db.query(User).filter(User.id == 12).update({User.age:12})
# 上面这句返回的是id
self.db.commit()

二、使用赋值方法

userInfo = self.db.query(User).get(12)
if userInfo:  # 这是对象
    userInfo.age = 12
    self.db.commit()

问题:使用sqlalchemy如何按月统计数据

解决:使用原生sql语句,使用sqlalchemy的execute方法

方法:

sks_months = self.db.execute("select month(end_time) as month
   , sum(used_time) as used_time from student_kejian_stats where
    student_id = %d and end_time > %s group by month" % (cuid, year))
    .fetchall()

select DATE_FORMAT(create_time,'%Y%m%d') days,count(caseid) count from tc_case group by days;
select DATE_FORMAT(create_time,'%Y%u') weeks,count(caseid) count from tc_case group by weeks;
select DATE_FORMAT(create_time,'%Y%m') months,count(caseid) count from tc_case group by months;

阅读全文