最近有个业务有点小变动,列表展示需要加上Customer消费笔数跟最后消费时间;
从视图copy下来的sql
SELECT `uprecord`.`SHOP` AS `SHOP`, `uprecord`.`SHOP_NAME` AS `SHOP_NAME`, `uprecord`.`SAREA` AS `SAREA`, `uprecord`.`SAREA_NAME` AS `SAREA_NAME`, `uprecord`.`TEL` AS `TEL`
, `uprecord`.`VIPID` AS `VIPID`, `uprecord`.`NAME` AS `NAME`, `uprecord`.`CARD_NO` AS `CARD_NO`, `uprecord`.`OLD_LEVEL` AS `OLD_LEVEL`, `uprecord`.`OLD_LEVEL_NAME` AS `OLD_LEVEL_NAME`
, `uprecord`.`NEW_LEVEL` AS `NEW_LEVEL`, `uprecord`.`NEW_LEVEL_NAME` AS `NEW_LEVEL_NAME`, `uprecord`.`IFMEET` AS `IFMEET`, `uprecord`.`IFMEET_NAME` AS `IFMEET_NAME`, `uprecord`.`REMARK` AS `REMARK`
, `uprecord`.`ID_` AS `ID_`, `uprecord`.`REF_ID_` AS `REF_ID_`, `uprecord`.`PARENT_ID_` AS `PARENT_ID_`, `uprecord`.`INST_ID_` AS `INST_ID_`, `uprecord`.`INST_STATUS_` AS `INST_STATUS_`
, `uprecord`.`TENANT_ID_` AS `TENANT_ID_`, `uprecord`.`CREATE_TIME_` AS `CREATE_TIME_`, `uprecord`.`CREATE_BY_` AS `CREATE_BY_`, `uprecord`.`UPDATE_BY_` AS `UPDATE_BY_`, `uprecord`.`UPDATE_TIME_` AS `UPDATE_TIME_`
, `uprecord`.`GROUP_ID_` AS `GROUP_ID_`, `uprecord`.`STATUS` AS `STATUS`, `uprecord`.`STATUS_NAME` AS `STATUS_NAME`, '消费记录' AS `XFJL`
, ifnull(`points`.`thisamount`, 0) AS `thisamount`
, ifnull(`points`.`use_thispoints`, 0) AS `use_thispoints`
, (
SELECT COUNT(0)
FROM `crmp_vip_salerecord`
WHERE year(`crmp_vip_salerecord`.`sDate`) = year(now())
AND `crmp_vip_salerecord`.`card_no` = `uprecord`.`CARD_NO`
) AS `consumption`
, (
SELECT `crmp_vip_salerecord`.`sDate`
FROM `crmp_vip_salerecord`
WHERE `crmp_vip_salerecord`.`vipid` = `uprecord`.`VIPID`
ORDER BY `crmp_vip_salerecord`.`sDate` DESC
LIMIT 0, 1
) AS `lastTime`
FROM `crmp_vip_uprecord` `uprecord`
LEFT JOIN `crmp_vip_points` `points` ON `points`.`vipid` = `uprecord`.`VIPID`
ORDER BY `uprecord`.`CREATE_TIME_`
运行sql是毫秒级别!
把他创建成视图之后的速度
整个人蒙蔽的状态,满脑子小朋友你是否有很多❓❓❓
用explain查看了下
除了 uprecord 没走索引(有同学就会问了为啥没走索引https://blog.csdn.net/qq_20009015/article/details/91405186
这个文章已经解释了,这不是本文章的重点。)其他都走了索引,整个人又是❓❓❓
然后又查看了下视图
出现了一个奇怪的表<derived2>,没错这个就是派生表;
派生表:Microsoft公司新推出的SQL2005数据库的一个增强功能。它将子查询做为一个表来处理,这个由子查询得出的新表就是我们说的“派生表”。
生成:比如要查找一个叫张铁牛的人的信息,我们知道他是男性,为了缩小查找范围我把所有的男性都找出来,然后从这些男性中里面再去找张铁牛。这里男性的集合就相当于派生表,转成sql语句是这样:select 姓名,住址,身份证 from (select * from 表名 where 性别='男性') t where 姓名='张铁牛'
这两条子查询的情况下就会产生派生表了;证明如下:
问题是找到了,可怎么在sql优化又是一个难题(默认是全部不加where条件);暂时考虑后期在表上做冗余数据,😅ahhhhh~~~先把功能上上去。
如果有描述不对的地方请大声的告诉作者你你你这这这错了!,如果有sql优化方案也可以在下方积极评论哦;