【1】Mysql Lua语言拼接实例

(1)基本语句

local sql = "select * from task_control where cycle_id = '" .. args["cycleid"] .. "' and state = 6;"
local sql = "update task_control set state = 7 where cycle_id = '" .. args["cycleid"] .. "';"
local sql = "select sum(if(cycle_low > 0, if(cycle_low > lastbalance, lastbalance, cycle_low), lastbalance)) 'gift' from cfg_acct_free_res " ..
    " where product_id = '" .. args["productid"] .. "' and call_type & " .. args["calltype"] ..
    " > 0 and disable_time > sysdate() and enable_time < sysdate();"
local sql = "select lastbalance 'cash' from cfg_subscriber_prepay " ..
" where product_id = '" .. args["productid"] .. "' and " ..
" disable_time > '" .. cycleid_str .. "01' and enable_time < '" .. getNextcyceid(cycleid_str) .. "01' " ..
" order by id DESC LIMIT 1;"
local sql = "select fee_rate 'fee_rate' from cfg_fee_rate c where c.product_id = '" .. args["productid"] .."' and call_type & " .. args["calltype"] ..
" > 0 and disable_date > sysdate() and enable_date < sysdate() order by level ASC limit 1;"
local sql = 'call sdrrating(\'' .. args["account"] .. '\', \'' .. args["cycleid"] .. '\');'
local sql = "select id, product_id, start_time, end_time, call_type from bill_user_special where " ..
    " cycle_id = '" .. cycleid_str .. "' and (isnull(process_cycleid) or process_cycleid <> '" .. cycleid_str .. "') " ..
    " order by product_id;"
local sql = "update view_dat_sdr_" .. cycleid_str .. " set service_qty = floor((duration + fee_unit - 1) / fee_unit), " ..
    " service_fee = floor((duration + fee_unit - 1) / fee_unit) * fee_rate " ..
    " where product_id = '" .. user["product_id"] .. "' and call_type = 1;"

(2)replace into 语句

local sql = "replace into dat_bill_" .. args["cycleid"] .. "(" ..

    "custom_id," ..           -- 2
    "contract_id," ..         -- 3
    "product_id," ..          -- 4
    "call_type," ..           -- 5
    -- 总费用
    "total_fee," ..           -- 6
    "total_duration," ..      -- 7
    "total_times," ..         -- 8 

    -- 结算费用  

    -- 过程控制*/

    ") select '" ..
    args["cycleid"] .. "'," ..  -- 1
    "''," ..                    -- 2
    "''," ..                    -- 3
    "product_id," ..            -- 4
    "call_type," ..             -- 5 

    -- 总费用
    "sum(service_fee)," ..      -- 6
    "sum(duration)," ..         -- 7 

    "0," ..                     -- 9
    "0," ..                     -- 10 

    -- 结算费用
    "source," ..                -- 11
    "sum(duration)," ..         -- 12
    "count(*)," ..              -- 13
    "sum(np_fee)," ..           -- 14 

    -- 过程控制
    "'00'," ..                  -- 15 

    " from view_dat_sdr_" .. args["cycleid"] .. " where product_id = '" .. args["account"] .. "' group by call_type;"

(3)TRUNCATE TABLE 语句

local sql = "TRUNCATE TABLE cfg_subscriber_prepay;" ..
" INSERT INTO cfg_subscriber_prepay SELECT * FROM cfg_subscriber_prepay_" .. args["cycleid"] .. ";" ..
" DROP TABLE cfg_subscriber_prepay_" .. args["cycleid"] .. "; commit;"
local undoSql = "START TRANSACTION;" ..
    " REPLACE INTO cfg_subscriber_prepay " ..
    " SELECT * FROM cfg_subscriber_prepay_" .. args["cycleid"] .. " WHERE product_id = '" .. args["productid"] .. "';" ..
    " DELETE FROM cfg_subscriber_prepay_" .. args["cycleid"] .. " WHERE product_id = '" .. args["productid"] .. "';" ..
    " REPLACE INTO cfg_acct_free_res " ..
    " SELECT * FROM acct_free_res_" .. args["cycleid"] .. " WHERE product_id = '" .. args["productid"] .. "';" ..
    " DELETE FROM acct_free_res_" .. args["cycleid"] .. " WHERE product_id = '" .. args["productid"] .. "';" ..
    " DELETE FROM cfg_prepay_history WHERE product_id = '" .. args["productid"] .. "' AND cycle_id = '" .. args["cycleid"] .. "';" ..
    " DELETE FROM dat_bill_" .. args["cycleid"] ..
    " WHERE cycle_id = '" .. args["cycleid"] .. "' AND product_id = '" .. args["productid"] .. "' AND call_type = '1048576';" ..
    " COMMIT;"

(4)SUM

local np_sum_fee = "SELECT product_id, IFNULL(SUM(duration), 0) AS np_sum_duration, COUNT(id) AS np_sum_cdrCnt, " ..
" IFNULL(SUM(service_qty), 0) AS np_service_qty, IFNULL(SUM(service_fee), 0) AS np_service_fee, " ..
" IFNULL(SUM(np_fee), 0) AS np_sum_fee, IFNULL(SUM(original_fee), 0) AS np_sum_original_fee " ..
" FROM np_cdr_" .. cycleid .. " WHERE product_id = '" .. record["product_id"] .. "';"

(5)整体过程

local select_productid = "select product_id from np_cdr_" .. cycleid .. " group by product_id;"
local rtn, productid_set = executeSql(select_productid)
if rtn then

local sql_const = "insert into compare_fee_" .. cycleid .. " (product_id, np_id, np_sum_duration, np_total_times, " ..
"np_sum_qty, np_sum_fee, un_sum_duration, un_total_times, un_sum_fee, sum_np_fee, sum_original_fee) values "
if type(productid_set) == 'table' and next(productid_set) ~= nil then
    for key, record in pairs(productid_set) do
        local amount_table = {}
        amount_table["product_id"] = record["product_id"]
        amount_table["np_id"] = 'all'
        -- 【1】统计
        local np_sum_fee = "SELECT product_id, IFNULL(SUM(duration), 0) AS np_sum_duration, COUNT(id) AS np_sum_cdrCnt, " ..
        " IFNULL(SUM(service_qty), 0) AS np_service_qty, IFNULL(SUM(service_fee), 0) AS np_service_fee, " ..
        " IFNULL(SUM(np_fee), 0) AS np_sum_fee, IFNULL(SUM(original_fee), 0) AS np_sum_original_fee " ..
        " FROM np_cdr_" .. cycleid .. " WHERE product_id = '" .. record["product_id"] .. "';"
        local rtn, desc = executeSql(np_sum_fee)
        if rtn and next(desc) ~= nil then
            amount_table[]["np_sum_duration"]
            amount_table[]["np_sum_cdrCnt"]
            amount_table[]["np_service_qty"]
            amount_table[]["np_service_fee"]
            amount_table[]["np_sum_fee"]
            amount_table[]["np_sum_original_fee"]
        end
        -- 【2】汇总
        local un_sum_fee = "SELECT product_id, IFNULL(SUM(total_duration), 0) AS un_sum_duration, IFNULL(SUM(total_times), 0) AS un_sum_cdrCnt, " ..
        " IFNULL(SUM(total_fee), 0) AS un_sum_fee FROM dat_bill_" .. cycleid .. " WHERE call_type & 4097 > 0 AND product_id = '" .. record["product_id"] .. "';"
        local rtn, desc = executeSql(un_sum_fee)
        if rtn and next(desc) ~= nil then
            amount_table[]["un_sum_duration"]
            amount_table[]["un_sum_cdrCnt"]
            amount_table[]["un_sum_fee"]
        end
        -- 构建sql语句
         then
            insert_sql = insert_sql .. ","
        else
            insert_sql = sql_const
        end
        insert_sql = insert_sql .. "('" ..
        amount_table["product_id"] .. "', '" ..
        amount_table["np_id"] .. "', " ..
        () .. ", " ..
        () .. ", " ..
        () .. ", " ..
        () .. ", " ..
        () .. ", " ..
        ().. ", " ..
        () .. ", " ..
        () .. ", " ..
        () .. ")"
        value_count = value_count +
         == value_count then
            sum_count = sum_count + value_count
            insert_sql = insert_sql .. "; commit;"
            local rtn, result = executeSql(insert_sql)
            if not rtn then
                rtnstr[
                rtnstr["msg"] = "Error. amount_sum_fee insert into sum_fee num : " .. sum_count .. " sql : " .. insert_sql
                return false
            else
                local result = "compare: success to amount_sum_fee insert into sum_fee num : " .. sum_count
                ngx.log(ngx.ERR, result)
            end
            insert_sql = ""
            value_count =
        end
    end
     then
        sum_count = sum_count + value_count
        insert_sql = insert_sql .. "; commit;"
        local rtn, result = executeSql(insert_sql)
        if not rtn then
            rtnstr[
            rtnstr["msg"] = "Error. amount_sum_fee insert into sum_fee num : " .. sum_count .. " sql : " .. insert_sql
            return false
        else
            local result = "compare: success to amount_sum_fee insert into sum_fee num : " .. sum_count
            ngx.log(ngx.ERR, result)
        end
        insert_sql = ""
        value_count =
    end
end

(6)常量sql 拼接其他sql语句

local insert_const_sql = "insert into dat_bill_" .. cycleid_str .. "(" ..

    " custom_id," ..           -- 2
    " contract_id," ..         -- 3
    " product_id," ..          -- 4
    " call_type," ..           -- 5 

    -- [1]
    " total_fee," ..           -- 6
    " total_duration," ..      -- 7
    " total_times," ..         -- 8 

    -- [2]
    " np_id," ..               -- 11
    " np_duration," ..         -- 12
    " np_times," ..            -- 13
    " np_fee," ..              -- 14 

    -- [3]

local select_sql = "select " ..
    "product_id, " ..                         -- 4
    "call_type, " ..                          -- 5 

    -- [1]
    "IFNULL(sum(service_fee), 0) as un_total_fee, " ..   -- 6
    "IFNULL(sum(duration), 0) as total_duration, " ..    -- 7
    "count(*) as total_times, " ..                       -- 8 

    -- [2]
    "source, " ..                                     -- 11
    "IFNULL(sum(np_fee), 0) as np_total_fee, " ..     -- 14 integer NULL,

    -- [3]

    " from view_dat_sdr_" .. cycleid_str .. " where product_id = '" .. productid .. "' and call_type & " .. calltype .. " > 0 " ..
    " and (reserve_00 = '0' OR reserve_00 = '2') group by call_type;"
local rtn, desc = executeSql(select_sql, cfg.is_master_bill)
if not rtn then
    rtnstr[
    rtnstr["msg"] = "failed to genBill select data cycleid : " .. cycleid_str .. " productid : " .. productid .. " error : " .. desc
    ngx.log(ngx.ERR, rtnstr["msg"])
else
    if type(desc) == "table" and next(desc) ~= nil then
        local insert_sql = ""
        for key, value in ipairs(desc) do
            insert_sql = insert_sql .. insert_const_sql
            insert_sql = insert_sql .. "('" .. cycleid_str .. "', '', '', '" .. productid .. "', " .. value["call_type"] .. ", " ..
            value["un_total_fee"] .. ", " .. value["total_duration"] .. ", " .. value["total_times"] .. ", 0, 0, '" ..
            value["source"] .. "', " .. value["total_duration"] .. ", " .. value["total_times"] .. ", " .. value["np_total_fee"] .. ", '00', '" ..
            value["current"] .. "', '" .. value["current"] .. "')" ..
            " ON DUPLICATE KEY UPDATE" ..
            " total_fee = " .. value["un_total_fee"] .. ", total_duration = " .. value["total_duration"] .. "," ..
            " total_times = " .. value["total_times"] .. ", np_duration = " .. value["total_duration"] .. "," ..
            " np_times = " .. value["total_times"] .. ", np_fee = " .. value["np_total_fee"] .. "," ..
            " insert_time = '" .. value["current"] .. "', update_time = '" .. value["current"] .. "'; "
        end
        --ngx.log(ngx.ERR, "genBill insert into dat_bill_" .. cycleid_str .. " insert_sql : " .. insert_sql)
        local rtn, err = executeSql(insert_sql)
        if not rtn then
            rtnstr[
            rtnstr["msg"] = "Error. failed to genBill insert into dat_bill_" .. cycleid_str .. " productid : " .. productid ..
            " call_type : " .. value["call_type"] .. " error : " .. err
            ngx.log(ngx.ERR, rtnstr["msg"])
        end
    else
        rtnstr[
        rtnstr["msg"] = "OK. genBill bill productid : " .. productid .. " cycleid : " .. cycleid_str .. " is empty"
        ngx.log(ngx.ERR, rtnstr["msg"])
    end
end

(7)命令LOAD DATA INFILE

lcoal sql = "LOAD DATA INFILE '" .. csvdir .. string.gsub(offlinefile["filename"], ".zip", ".csv") .. "' " ..
"INTO TABLE np_cdr_" .. cycleid_str .." FIELDS TERMINATED BY ',' IGNORE 1 LINES (product_id,calling_id,start_time,duration,call_type,@fee) "  ..
"set original_fee = @fee * 1000, insert_time = sysdate(), " ..
"np_id = '" .. offlinefile["np_id"] .. "'," ..
"cdr_state = '00', " ..
"source = '" .. offlinefile["filename"] .. "';"

(8)IFNULL 和 FLOOR函数

local sql = "select call_type, ani_area, dnis_area, fee_rate, fee_unit, fee_type, transfer_area, " ..
    " ifnull(np_id,'none') 'np_id', " ..
    " ifnull(to_days(enable_date) - TO_DAYS('19700101') - 1, 0) 'startdate', " ..
    " ifnull(to_days(disable_date) - TO_DAYS('19700101') + 1, 0) 'enddate'" ..
    " From cfg_fee_rate where product_id = '" ..
    productid .. "' and (fee_type = 'voice' or fee_type = 'sms') order by level DESC, enable_date DESC;"
local update_sql = "update np_cdr_" .. cycleid_str ..
" set np_unit = IF(call_type = '长话', " .. long_rate["fee_unit"] .. ", " .. short_rate["fee_unit"] .. "), " ..
" np_rate = IF(call_type = '长话', " .. long_rate["fee_rate"] .. ", " .. short_rate["fee_rate"] .. "), "..
" np_qty = FLOOR((duration + np_unit - 1) / np_unit), " ..
" np_fee = FLOOR((duration + np_unit - 1) / np_unit) * np_rate " ..
" where np_id = '" .. offlinefile["np_id"] .. "' and source = '" .. offlinefile["filename"] .. "';"

(9)distinct关键字

local sql = "select distinct a.id, a.product_id, a.realbalance, a.balance " ..
    " from cfg_subscriber_prepay a " ..
    " where a.status = '01' and a.disable_time > '" .. lastyearmonth .. "01' and " ..
    " a.enable_time < '" .. (getNextcyceid(lastyearmonth)) .. "01' order by a.product_id, a.id;"

(10)常量值语句

local sqlstr = "replace into dat_bill_" .. cycleid_str .. "(cycle_id, custom_id, contract_id, product_id, call_type, total_fee," ..
" total_duration, total_times, discount_fee, cash_fee, np_id, np_duration, np_times, np_fee," ..
" bill_state, insert_time, update_time) select '" .. cycleid_str ..
"' , '+', '+', product_id, call_type, fee_rate" ..
", 1, 1, 0" ..
", 0, '0', 1, 1, 0, '0', sysdate(), sysdate() from cfg_fee_rate where call_type & ".. string.format("%d", cfg.globalcalltypecode['service']) .. " > 0 and disable_date >= '" ..
getNextcyceid(cycleid_str) .. "01' and enable_date < '" .. getNextcyceid(cycleid_str) ..  "01' order by product_id;" 

(11)ON DUPLICATE KEY UPDATE 语句

local sqlstr = "update cfg_acct_free_res set " .. computebalance .. " = " ..
    string.format("%d", fr_record[refbalance] - fr_record["cycle_low"]) ..
    " where id = " .. fr_record["id"] .. ";"

sqlstr = sqlstr .. "insert into dat_bill_" .. cycleid_str .. "(cycle_id, custom_id, contract_id, product_id, call_type, total_fee," ..
    "total_duration, total_times, discount_fee, cash_fee, np_id, np_duration, np_times, np_fee," ..
    "bill_state, insert_time, update_time) values('" .. -- values
    cycleid_str ..
    "', '+', '+', '" .. freeresproduct .."', 131072," ..
    string.format("%d", fr_record["cycle_low"] - fr_record["resumesum"]) ..
    ", 1, 1," ..
    string.format("%d", fr_record["cycle_low"] - fr_record["resumesum"]) ..
    ", 0, '0', 1, 1, 0, '0', sysdate(), sysdate()) on duplicate key update " .. -- on duplicate key update
    "total_fee = total_fee + " .. string.format("%d", fr_record["cycle_low"] - fr_record["resumesum"]) .."," ..
    "discount_fee = discount_fee + " .. string.format("%d", fr_record["cycle_low"] - fr_record["resumesum"]) .."," ..
    "total_times = total_times + 1;"

Good Good Study, Day Day Up.

顺序 选择 循环 总结

Mysql Lua语言拼接的更多相关文章

  1. 【quick-cocos2d-x】Lua 语言基础

    版权声明:本文为博主原创文章,转载请注明出处. 使用quick-x开发游戏有两年时间了,quick-x是cocos2d-Lua的一个豪华升级版的框架,使用Lua编程.相比于C++,lua的开发确实快速 ...

  2. Lua语言中文手册 转载自网络

    Programming in LuaCopyright ® 2005, Translation Team, www.luachina.net Programming in LuaProgramming ...

  3. 用VC编译lua源码,生成lua语言的解释器和编译器

    用VC编译lua源码,生成lua语言的解释器和编译器 1.去网址下载源码 http://www.lua.org/download.html 2.装一个VC++,我用的是VC6.0 3.接下来我们开始编 ...

  4. 51CTO专访淘宝清无:漫谈Nginx服务器与Lua语言

    http://os.51cto.com/art/201112/307610.htm 说到Web服务器,也许你第一时间会想到Apache,也许你会想到Nginx.虽然说Apache依然是Web服务器的老 ...

  5. lua语言入门之Sublime Text设置lua的Build System

    转自: http://blog.csdn.net/wangbin_jxust/article/details/8911956 最近开始学习LUA语言,使用Sublime Text作为编辑器,不得不说, ...

  6. 编译并使用Lua语言

    Lua是一个小巧的脚本语言,该语言设计的目的是为了嵌入应用程序中,从而为应用程序提供灵活的扩展和定制功能. 可扩展性.Lua的扩展性非常卓越,可以通过Lua代码或C代码扩展,很多功能可以通过外部库来扩 ...

  7. Lua语言在Wireshark中使用(转)

    1.       检查Wireshark的版本是否支持Lua 打开Wireshark,点击“HelpàAbout Wireshark”菜单,查看弹出的对话框,如果有“with Lua 5.1”表示支持 ...

  8. Mysql C语言API编程入门讲解

    原文:Mysql C语言API编程入门讲解 软件开发中我们经常要访问数据库,存取数据,之前已经有网友提出让鸡啄米讲讲数据库编程的知识,本文就详细讲解如何使用Mysql的C语言API进行数据库编程.   ...

  9. Unity进阶----Lua语言知识点(2018/11/08)

    国内开发: 敏捷开发: 集中精力加班堆出来第一个版本 基本没啥大的bug 国外开发: 1).需求分析: 2).讨论 3).分模块 4).框架 5).画UML图(类图class function)(e- ...

随机推荐

  1. drf常用方法

    1.认证 2.权限 3.序列化 4.分页 5.限流

  2. pandas模块中序列Series和列表List的区别

    列表:输出结果在中括号中,且各元素之间以逗号分隔 序列:竖着的形式展示数据 print("列表的输出形式:") a=[1,2,3,4] print(a) print(type(a) ...

  3. pipelinewise 基于singer 指南的的数据pipeline 工具

    pipelinewise 是基于开源singer 指南开发的数据pipeline工具,与singer tap 以及target 兼容 支持的特性 内置的elt 特性 轻量级 支持多种复制方法,cdc( ...

  4. How to Construct the Input Bet String

    The purpose of this section is to describe the format of the string which will submitted to the Pyth ...

  5. 【题解】洛谷 P1080 国王游戏

    目录 题目 思路 \(Code\) 题目 P1080 国王游戏 思路 贪心+高精度.按\(a \times b\)从小到大排序就可以了. \(Code\) #include<bits/stdc+ ...

  6. python格式化输出之format用法

    format用法 相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’ 使用方法由两种:b ...

  7. gitlab 上传代码

    #生成公钥ssh-keygen -t ed25519 -C "xxx@tianwang.com"#拷贝公钥pbcopy < ~/.ssh/id_ed25519.pub 在网页 ...

  8. Octopus501工作站 安装记录

    cmake libreadline-dev 没有运行程序,nvidia-smi查看GPU-Util 达到100% 解决方案:需要把驱动模式设置为常驻内存才可以,设置命令:nvidia-smi -pm ...

  9. 树莓派3B+红外配置

    sudo apt-get install lirc /etc/lirc/lirc_options.conf #driver = devinput driver = default #device = ...

  10. mstar gdb调试

    当进程崩溃出现coredump提示时,可以利用gdb来定位出错函数. 首先,把core_dump.XXX.gz文件从设备上拷贝出来,放到编译环境下,另外,还要把代码目录下的symbols文件夹也拷贝到 ...