MySql:我可以使用sql创建数组吗?



我正在使用Mysql DB。 我的问题是:我可以使用SQL创建数组吗?如果是,那么如何以及如何使用以下查询的输出填充此数组 - "从表名中选择column_name1"。 帮帮我,提前谢谢

正如我在评论中提到的,MySQL本身不支持数组。其他编程语言(如PHP,Java,Python等)支持这种结构,您可以编写一个能够连接到MySQL数据库的程序,从中读取数据并填充数组(我认为PostgreSQL支持数组数据类型,但我不确定)。

可以执行的操作是在存储过程中使用游标从查询中检索数据并将其存储到变量中。

例:

delimiter $$
create procedure my_procedure()
begin
    declare value varchar(100);
    declare done int default false;
    declare cur cursor for
        select column_name1 from your_table;
    declare continue handler for not found set done = true;
    open cur;  -- This line will open the row set and place the cursor
               -- on the first row.
    loop_data: loop
        fetch cur into value; -- This line will fetch the current row
                              -- into the variable and move the cursor
                              -- to the next row.
        if done then          -- If there are no more rows in the
            leave loop_data;  -- row set, the loop is terminated here
        end if;               -- and the execution moves to the next
                              -- instruction after "end loop;"
        -- do whatever you need to do with the retrieved value
    end loop;
    close cur;
end $$
delimiter ;

如果要使用高级编程语言中的数组,可以使用适当的方法进行操作。下面是一个使用 Java 的示例(有关详细信息,请参阅 Java 教程:JDBC 数据库访问):

public class SomeClass {
    /*
      Retrieve data from a database and return an array with it.
      Parameters:
       - conn: Connection to the database. 
     */
    public String[] getValues(Connection conn) {
        String[] ans = new String[10];
        int i;
        try(
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(
                               "select column_name1 from your_table limit 10"
                           );
        ) {
            rs.beforeFirst();
            i = 0;
            while(rs.next()) {
                ans[i] = rs.getString("column_name1");
                i++;
            }
        } catch(SQLException e) {
            // Code to handle the SQL exception
        }
        return ans;
    }
}

引用:

  • MySQL 参考手册:游标

您可以使用变量简单地将行值select为字符串。不完全是一个数组,但它允许您将所有值存储到单个变量中:

-- load test data
create table tableName (column_name1 varchar(5));
insert into tableName values
  ('abcde');
insert into tableName values
  ('fghij');
insert into tableName values
  ('klmno');
insert into tableName values
  ('pqrst');
insert into tableName values
  ('uvwzy');
insert into tableName values
  ('z');
-- build "array"
set @array := '';
select @array := concat(@array,column_name1) as array
from tableName;
select @array;

最新更新