php - 在mysql查询中创建和更新虚拟列值

标签 php mysql codeigniter

我的表结构是

customer  column1 column2(int) 
  1        sale      2            
  1        return    1            
  1        sale      3             
  1        sale      1             
  1        return    1  

问题:-

create a virtual column(column3) which has start value `column3 = 0` and update its value according to `column1` and `column2` values. I could not find a query which create and update a virtual column together.

例如IF(column1='销售',column3 +column2,column3-column2)

// start value of column3 = 0 for each product
customer  column1 column2(int) column3
  1        sale      2             2  //0+2 because it is a sale 
  1        return    1             1  //2-1 because it is a return 
  1        sale      3             4  //1+3 because it is a sale 
  1        sale      1             6  //4+2 because it is a sale 
  1        return     1            4  //6-2 because it is a return 

最佳答案

CROSS JOIN 应该可以解决这个问题:

SELECT
    t.column1,
    t.column2,
    CASE
WHEN t.column1 = 'sale' THEN
    @id :=@id + t.column2
ELSE
    @id :=@id - t.column2
END AS column3
FROM
(SELECT @id:=0) var
CROSS JOIN table1 t

关于php - 在mysql查询中创建和更新虚拟列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35602662/

相关文章:

MySQL : double IN() statement

php - 显示来自 blob mysql 的图像

php - 路由问题 CodeIgniter

php - CodeIgniter 中日期和时间的验证规则

javascript - 如何克隆该行并确保每行中的所有日期选择器都正常运行?

php - 正则表达式:如何不替换任何 html 标签中的特定单词?

php - Laravel hasMany 具有基于附加关系的条件

php - MySQL 使用 Substring 和 Like 仅连接部分字段

php - 错误号 : 1064 CodeIgniter

php - 如何从源代码运行 Composer 和/或允许使用 PhpStorm 进行逐步调试?