mysql - 我的 Sql 查询复制列中的值

标签 mysql phpmyadmin

我在创建 SQL 查询时遇到问题。我遇到这样的情况

ColumnA    ColumnB    ColumnC

1 4 text123

1           5
1           6 
1           7

如何进行查询以自动填充第 C 列第 1/4 行的值?

我想要:如果columnA Value = 1并且ColumnB Value = 5并且ColumnC Value = NULL,则取A = 1和B = 4的ColumnC行的值并像这样填充ColumnC Value

Column A Column B Column C

1 4 text123

1        5         text123
1        6 
1        7

我需要这个用于其他条目,例如columnA = 2columnA = 3。

最佳答案

使用用户变量和 case 语句很容易做到:

请注意,此逻辑模拟其他 RDBM 系统中的滞后/超前分析/窗口函数。 MySQL 目前不支持窗口/分析函数。

Working DEMO:

SELECT ColumnA
     , ColumnB
     , case when columnC is null then @PriorVal 
            else @PriorVal:=ColumnC end as ColumnC
FROM YourTableName
CROSS JOIN (SELECT @PriorVal:='') z
ORDER BY ColumnA, ColumnB;

我们使用用户变量@PriorVal来跟踪不为空的C值,然后根据columnA、ColumnB的顺序用该值替换C中的空值。每次 columnC 具有非空值时,userVariable @PriorValue 都会设置为 C 并显示该值。只要columnC 具有NULL 值,就会显示存储的PriorVal userVariable。这种方法严重依赖于 order by。

@PriorVal 在上面的交叉连接派生表 (z) 中初始化。此方法可以更轻松地与 PHP 结合使用,因为不需要传递两个单独的语句。

使用我的示例数据集:

Insert into foo_47514588 values 
   (1,4,'text123')
  ,(1,5,NULL)
  ,(1,6,NULL)
  ,(1,7,NULL)
  ,(1,8,'text2')
  ,(1,10,NULL)
  ,(2,1,'Text3');

它实现了以下目标:

+----+---------+---------+---------+
|    | ColumnA | ColumnB | COlumnC |
+----+---------+---------+---------+
|  1 |       1 |       4 | text123 |
|  2 |       1 |       5 | text123 |  <--Added by case statement
|  3 |       1 |       6 | text123 |  <--Added by case statement
|  4 |       1 |       7 | text123 |  <--Added by case statement
|  5 |       1 |       8 | text2   |
|  6 |       1 |      10 | text2   |  <--Added by case statement
|  7 |       2 |       1 | Text3   |
+----+---------+---------+---------+

关于mysql - 我的 Sql 查询复制列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47514588/

相关文章:

php - 基于SQL Dump建立SQL Server

mysql - 为什么 VARCHAR 变量不能在 mysql 存储过程中使用内部查询作为列名?

mysql - phpmyadmin 添加文本到字段

linux - 在centos 7上安装phpmyadmin的问题

MySQL 从时间戳字段创建日期时间字段

php - 为什么我的左连接在我的 php mysql 数据库中不起作用?

php - (MySQL) 按字段分组并选择 COUNT(字段) 和分组行数

java - 生成唯一的注册号

mysql - php my admin 一对多关系

php - 从mysql中提取序列化数据