Increment column value by 1 while insert..select join

问题描述 投票:0回答:0

我有 3 个表 table_1、table_2 和 table_3。

我正在尝试通过 table_1 和 table_2 的连接将数据插入 table_3(该表中已经存在一些行)。

table_3
有以下列:

unique_id  - its unique id needs to be increment by 1 from its last value
client_key - should get from table_1.client_key
xcolumn    - should get from table_2.xcolumn
xxcolumn   - this column value depend on table_3.xcolumn (below I mentioned which value should be here) 
         if table_3.xcolumn contains any of this value (purchase some things,purchase) xxcolumn should be PURCHASE 
         if table_3.xcolumn contains any of this value (cash advance,ATM,promo cashing) xxcolumn should be CASH
         if table_3.xcolumn contains any of this value (promo,promo deal) xxcolumn should be PROMO
         if table_3.xcolumn doest not contains any above value then xxcolumn should be OTHER
xycolumn   - this column value depend on table_3.xxcolumn (below I mentioned which value should be here)
         if table_3.xxcolumn is PURCHASE xycolumn should be 1 
         if table_3.xxcolumn is CASH xycolumn should be 2
         if table_3.xxcolumn is PROMO xycolumn should be 3
         if table_3.xxcolumn is OTHER xycolumn should be 4           
ycolumn    - should get from table_2.ycolumn

我试过下面的插入查询:

insert into table_3 (unique_id, client_key, xcolumn, xxcolumn, xycolumn, ycolumn)  
    select
        (select max(unique_id) + 1 
         from table_3),
        table_1.client_key, table_2.xcolumn,
        'cash', 1, table_2.ycolumn 
    from 
        table_2  
    inner join 
        table_1 on table_2.client_id = table_1.client_id;

但是对于 unique_id 我无法在加入时将其值增加 1,如果有超过一行(不是每一行都只增加一次)。

我也无法弄清楚如何获得 xxcolumn,xycolumn 值。

供参考。我用 table_1,table_2,,table_3 创建了 sql fiddle

http://sqlfiddle.com/#!9/8a48477/2

mysql sql mariadb
© www.soinside.com 2019 - 2024. All rights reserved.