mysql - 创建动态 mysql 查询

标签 mysql

是否可以创建一个sql文件,它可以获取两个数字参数并在循环中使用它们,在每次迭代中我们都会使用这两个参数替换为指令,并在循环结束时递增它们?

有人可以告诉我该怎么做吗?

编辑:考虑我想更新名为邮政编码的表,我想以这种方式插入新的代码:
您会得到两个数字参数。 第一个是起始码例如:1000 第二个是要添加的顺序代码的数量,比如说 5。 因此,您将使用 1000、1001...1004 更新表格

最佳答案

SQL 查询不能执行循环,但您可以通过生成一些数据来“模拟”它们,然后以声明的方式描述您想要对它们执行的操作:

-- your input variables
set @start = 1000;
set @count = 5;

select val as zip from (
  -- generate some numbers starting with the value of @start
  select @start + (a.a + (10 * b.a) + (100 * c.a)) as val
    from (
      -- this creates cross join of 3 tables of numbers 0-9
      -- so the select up there gets rows with values 0-999
      -- you can add another cross join and 1000*d.a to get 0-9999
      select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
        cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
        cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
  ) tmp
-- we should generate enough numbers to always cover the needs
-- then this condition will filter only currently needed values
where (val >= @start) and (val < @start + @count)

查看http://sqlfiddle.com/#!9/9eecb7d/17037

我在少数情况下使用它来生成某些日期之间的所有日期(主要是为了填补报告数据的空白),即使我尝试很大的数字,它的速度也出奇的快。但如果您知道 @count 的最大值是多少,您就可以使用该值。

关于mysql - 创建动态 mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32211847/

相关文章:

mysql - 将不存在的记录插入Mysql表中

php - 获取数组作为 AJAX 的响应

mysql - "select 2*2 as ' m ', (m*2) as ' n ';"返回错误

php - 保存 CSV 文件而不是下载

php - Android远程数据库连接使用PHP和JSON

mysql - 如何在 MySQL 中重新索引计数器以连续递增?

php - json_encode (PHP) + JSON_ARRAYAGG (mySQL) 中的反斜杠

mysql - 如何创建按特定百分比范围分组的 SQL 查询

PHP - 从 mySQL 服务器检索数据

php - 使用 php 嵌入多次从 mysql 获取行