要求:过期(分为库存为0和超出有效时间)的商品排在下面,在售状态的商品排在上面。之后再分别按照发布时间排序。
Sql语句如下:
select deadline, total_count, c_time from (
select *, 0 as ord from sale_goods where goods_type = 'sale-goods' and delete = false and total_count > 0 and deadline > now()
union
select *, 1 as ord from sale_goods where goods_type = 'sale-goods' and delete = false and (total_count <= 0 or deadline <= now())
) sale_goods_mall order by ord asc, c_time desc;
:return:
# 分页
pages = get_arg('pages', u'页码', default=1, parm_type=int)
limit = get_arg('limit', u'条数', default=30, parm_type=int)
# 总的数据sql
sql_str = "select * from (" \
"select *, 0 as ord from sale_goods where goods_type = 'sale-goods' and delete = false and total_count > 0 and deadline > now()" \
"union " \
"select *, 1 as ord from sale_goods where goods_type = 'sale-goods' and delete = false and (total_count <= 0 or deadline <= now())" \
") sale_goods_mall order by ord asc, c_time desc limit %d offset %d;" % (limit, limit * (pages - 1))
# 在售的数据sql
in_sale_sql = "select *, 0 as ord from sale_goods where goods_type = 'sale-goods' and delete = false and total_count > 0 and deadline > now();"
# sqlalchemy执行sql
data_query = db.session.execute(sql_str)
in_sale_query = db.session.execute(in_sale_sql)
# 获取查询到的数据条数
total = data_query.rowcount
sale_total = in_sale_query.rowcount
# fetchall()遍历到所有数据
data = {
'total': total,
'sale_total': sale_total,
'sale_goods': [{
'deadline': time_to_str(sale_goods['deadline'], only_date=True) or '',
'id_no': sale_goods['id_no'] or '',
'c_time': time_to_str(sale_goods['c_time'], only_date=True),
'deadline_invalid': True if float(time.mktime(sale_goods['deadline'].timetuple())) < float(time.time()) else False
}for goods in data_query.fetchall()]
}