Python-Flask:值得让我吐槽好久,铭记于心的SQL语句

一.它的由来是项目中的设备管理需求,需要俩个模型类,其中一个用来记录资产信息,另一个记录资产借用历史纪录,这就存在数据展示的连接问题,由于需要做筛选,而筛选的逻辑十分复杂,大致包括借用,归还,销毁,时间,模糊查询等操作。当时做了一天,还是被公司的老资格点醒的。来欣赏一下吧:

select t1.assetstatus, t1.assetnumber, t1.id, t2.user_name, t2.userdepartments, t2.output, 
t2.handel, t2.returndate, t2.borrowdate from fo_A t1 left join (select * from fo_B where
ID in (select ID from (select max(ID) as ID max(borrowdate) from fo_B group by 
assetnumber))) t2 on t1.assetnumber = t2.assetnumber where t1.assetstatus in (0, 1, 2)

二.它的由来是oracle-flask项目中查询数据页面展示分页需求,前端vue需要每一页的数据,和数据总条数(前端控件所控制)。由于此分页处理,需要被许多功能需求所需要,我们进行可功能性封装处理。

代码如下:

# 查询分页数据记录
def open_page_query(sql, pageindex, pagesize):
    pagesql = f"select * from (select (select count(1) from ({sql})) as sum, ROWNO as rowno, r.* from ({sql}) r where ROWNO <= {pageindex} * {pagesize}) form where form.rowno > ({pageindex} - 1) * {pagesize}"
    num = 0
    sqlalchemy = SQLALchemy(app)
    try:
        datas, err = sqlalchemy.conn.execute(pagesql)
    except Exception as err:
        return [], 0, err
    if datas:
        num = datas[0]['TOTAL']
        return datas, num, ''
    

sql语句如下:

f"select * from (select (select count(1) from ({sql})) as sum, ROWNO as rowno, 
r.* from ({sql}) r where ROWNO <= {pageindex} * {pagesize}) form where form.rowno > 
({pageindex} - 1) * {pagesize}"

三.它的由来是为了更新一系列相似的表格字段数据,为了获取到相关表格的表格名称。sql如下:

select table_name from user_all_tables where table_name like '%--%' order by table_name

四.它的由来是要查询一段时间内表中的日期数据,由于表中没有单纯的日期字段,只是由年,月,日的字符串字段。所以想要按照这个区间内取值,就按照一下sql语句实现:

select * from (select concat(concat(concat(concat(nian, '-'), case when 
to_number(yue) < 10 then concat('0', yue) else yue end), '-'), case when 
to_number(tian) < 10 then concat('0', tian) else tian end) as datetime, 
t.* from tab_table_week t ) t1 where t1.datetime<='2018-01-01' and 
datetime >= '2017-01-01'

 

 

 

你可能感兴趣的:(Flask项目)