MySQL在select语句中生成带有循环的列 [英] MySQL producing columns with loop in a select statement

查看:520
本文介绍了MySQL在select语句中生成带有循环的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MySQL中,我有一个函数,它接受一个数字参数,并根据该数字从另一个表中提取结果的子集。目前的实现如下所示:

In MySQL I have a function that takes a number argument and spits out a subset of results from another table, based on that number. Implementation currently looks like:


SELECT 
  id,
  date,
  function(do stuff with value 1) as t1,
  function(do stuff with value 2) as t2,
  function(do stuff with value 3) as t3,
  ...
  function(do stuff with value N) as tN
FROM table

您可以在select语句中使用循环(或者甚至是构建过程)

Can you use a loop in a select statement (or even a procedure that builds a table) so the above becomes:


SELECT
  id,
  date,
  LOOP x = 1 through N
    function(do stuff with value x) as tx,
  END LOOP
FROM table

感谢。

推荐答案

是的,您可以...查看DynamicSQL ..

yes you can... take a look into DynamicSQL..

下面是一个示例

和另一个例子

一般来说,您将创建一个包含要执行的SQL语句的字符串,然后对其进行准备,然后执行它。 ..

In general, you build a string that contains the SQL statement you want to execute, then prepare it, then execute it...

这篇关于MySQL在select语句中生成带有循环的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆