首页 > 代码库 > 表的数据很大筛选问题
表的数据很大筛选问题
当条件很大时,我们就不要用IN了。因为那样我们的sql语句就会很大,解决方法用临时表和 左连接加索引
public function run($daily = ‘‘){ $daily = is_numeric($daily) ? date(‘Y-m-d‘, $daily) : $daily; if(empty($daily)){ $daily = date(‘Y-m-d‘, time() - (60*60*24)); } // 创建临时表 $this->salesDailySales->execute("DROP TABLE IF EXISTS 000_sales_p"); $sql = "CREATE TABLE 000_sales_p SELECT orders_id,orders_platform,orders_import_date FROM orders WHERE orders_import_date=‘".$daily."‘ AND orders_status NOT IN (‘900‘,‘100‘)"; $returnInfo = $this->salesDailySales->execute($sql); if($returnInfo !== false){ // 给临时表添加索引 $this->salesDailySales->execute("ALTER TABLE 000_sales_p ADD INDEX (orders_id)"); // 生成临时表 000_tmp_op $this->salesDailySales->execute("DROP TABLE IF EXISTS 000_tmp_op"); $returnInfo = $this->salesDailySales->execute("CREATE TABLE 000_tmp_op SELECT p.orders_platform,p.orders_import_date, op.orders_product_quantity, op.product_id, op.orders_item_total_price_usd, IF(op.product_attr_code=99,1,op.product_attr_code) as product_attr_code FROM 000_sales_p p LEFT JOIN orders_product op ON p.orders_id = op.orders_id" ); if($returnInfo !== false){ // 添加 索引 product_id,product_attr_code $this->salesDailySales->execute("ALTER TABLE 000_tmp_op ADD INDEX (product_id)"); $this->salesDailySales->execute("ALTER TABLE 000_tmp_op ADD INDEX (product_attr_code)"); $sql = " INSERT INTO sales_daily_sales(product_attr_id,product_id,orders_platform,sales_daily_sales_date,daily_sales_qty,daily_sales_gmv) SELECT pa.product_attr_id, pa.product_id, op.orders_platform, op.orders_import_date, SUM( op.orders_product_quantity ), SUM(op.orders_item_total_price_usd) FROM 000_tmp_op op LEFT JOIN product_attr pa ON pa.product_id = op.product_id AND pa.product_attr_code = op.product_attr_code GROUP BY op.orders_import_date, op.orders_platform, product_attr_id"; // 添加数据之前 要删除同一天的数据 $map = array(); $map[‘sales_daily_sales_date‘] = $daily; $this->salesDailySales->where($map)->delete(); // 导入数据 $returnInfo = $this->salesDailySales->execute($sql); // 删除临时表 $this->salesDailySales->execute("DROP TABLE IF EXISTS 000_tmp_op"); $this->salesDailySales->execute("DROP TABLE IF EXISTS 000_sales_p"); if($returnInfo !== false){ return true; } } }
表的数据很大筛选问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。