• mysql为select结果集添加序号列


    两个函数简单搞定

    DELIMITER $$
    
    USE `oso_isp`$$
    
    DROP FUNCTION IF EXISTS `rownum_reset`$$
    
    CREATE FUNCTION `rownum_reset`() RETURNS INT(11)
    BEGIN
    	SET @rno = 0;   
    	RETURN 1; 
    END$$
    
    DELIMITER ;
    

      

    DELIMITER $$
    
    USE `oso_isp`$$
    
    DROP FUNCTION IF EXISTS `rownum`$$
    
    CREATE  FUNCTION `rownum`() RETURNS INT(11)
    BEGIN
    	/* 用法如: 
     		SELECT 
    		`rownum`(
    		)      AS `id`,
    		t.*
    		FROM TABLE t
    		WHERE rownum_reset() = 1
    	*/
    	
    	SET @rno = @rno + 1;   
    	RETURN @rno;  
        
        
    END$$
    
    DELIMITER ;
    

      

    查询结果测试

    测试代码:

    SELECT
      `rownum`(
    )			AS `row_num`
      ,`a`.`stock_in_date` 	AS `stock_in_date`
      ,`a`.`dinner_type`   	AS `dinner_type`
      ,`a`.`stockroom_id`  	AS `stockroom_id`
      ,SUM(`a`.`dinner_num`)
    			AS `dinner_num`
      ,SUM((SELECT SUM(`wh_stock_in_order_item`.`total_price`) FROM `wh_stock_in_order_item` WHERE (`wh_stock_in_order_item`.`stock_in_order_id` = `a`.`id`))) 
    			AS `total_price`
      ,COUNT(0)            	
    			AS `order_num`
      ,GROUP_CONCAT(DISTINCT (SELECT `staff`.`name` FROM `staff` WHERE (`staff`.`id` = `a`.`buyer_id`)) SEPARATOR ',') -- 行变列
    			AS `buyer_name`
    FROM `wh_stock_in_order` `a`
    WHERE ((`a`.`is_deleted` = 0)
           AND (`a`.`status` = 1)
           AND (`rownum_reset`() = 1)) -- 初始化序号列从1开始
    GROUP BY `a`.`stock_in_date`,`a`.`dinner_type`,`a`.`stockroom_id`
    ORDER BY `a`.`stock_in_date`,`a`.`dinner_type`
    

      

    返回结果:

      
                                                                                                        

    未来拿不出手,过去会有谁听。

    作者:aLong

    出处:http://www.cnblogs.com/keerdi/

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    C#封装(访问修饰符)和方法
    源文件声明规则和import、package
    throw和throws 的区别
    曲率计算
    react组件三大核心属性之一refs;react中的事件处理
    react脚手架,样式模块化
    es6 class类中可以直接写赋值语句
    es6 class类内部的方法自动开启了严格模式
    react脚手架
    react三大核心之一props
  • 原文地址:https://www.cnblogs.com/tooy/p/7281896.html
Copyright © 2020-2023  润新知