mysql利用视图提高开发效率

13 篇文章 0 订阅

前言:
最近在做一个商城,数据库原型图拿过来一个看,感觉需要查询表真多。前前后数了下,查询一个商品列表需要用到好几张表【效率问题后面再讨论】。感觉有点头晕。代码方面,觉得查询那么多表,容易出漏洞。于是为了简化代码,引入数据库视图。下面是结果图:

DROP VIEW  if exists SPecFilter ; 
CREATE VIEW SPecFilter(id,detail,name,cname,gname,regular_price,sale_price,promotion_price,spec,factory,image,category_id,goods_attr_id,attr_option_id) 
AS
select b.id,d.detail,c.name,a.cname,a.gname,b.regular_price,b.sale_price,b.promotion_price,b.spec,a.factory,f.image,g.id,c.id,d.id from t_goods_spu a, 
t_goods_sku b,t_goods_attr c,t_attr_option d ,t_sku_opt e,t_sku_image f, t_category g, t_category_spu h
where
a.default_sku_id=b.id 
and  e.sku_id=b.id
and  e.attr_id = c.id
and e.attr_id=c.id
and  e.option_id=d.id
and b.default_image_id = f.id
and h.spu_id = a.id
and h.category_id = g.id
and b.is_sale =1

反正就是头晕。如果在代码中写入这一波查询语句,会觉得头很晕。于是做了简化。做了视图后,我只要在代码中写一句:
select * from SPecFilter

        params = [category_id, start, _limit+1]
        with connection.cursor() as cs1:
            cs1.execute('select id, gname,factory,sale_price,regular_price,image,spec from SPecFilter where category_id=%s limit %s, %s', params) 
            ret1 = cs1.fetchall()
            if ret1 is None:
                logging.warning("无效的分类id")
                return Response(
                    self.write_json_page(limit=_limit, page=_page, hasNext=False, msg="无效的分类id", code=MsgCode.FAILURE))

总结:

对于复杂关联查询时,能够大大简化应用程序的代码。此外视图的查询效率基本上跟select 语句相差无几,可以认为没有任何性能上的损失。
其他参考链接:
https://www.cnblogs.com/geaozhang/p/6792369.html#yueshu

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值