mysql游标中使用的Group_Concat返回错误结果

时间:2017-10-23 17:07:07

标签: mysql stored-procedures cursor mariadb

以下代码应为csv2生成3个条目...但是会生成6个条目。

为什么?代码正在进行中。

创建代码:

Create table testing(
  idString varchar(20),
  region varchar(20)
);

insert into testing values("abcdefg","123456");
insert into testing values("bcdefgh","123456");
insert into testing values("cdefghi","123456");
insert into testing values("defghij","456789");
insert into testing values("efghijk","456789");
insert into testing values("fghijkl","456789");

要运行的代码:

DROP PROCEDURE IF EXISTS `sp_split`;
DROP PROCEDURE IF EXISTS `getCombinations`;

CREATE TABLE IF NOT EXISTS `temp` (
  `col` VARCHAR(100) NOT NULL
) ENGINE=MEMORY;

CREATE TABLE IF NOT EXISTS `result` (
  `col1` VARCHAR(100) NOT NULL
) ENGINE=MEMORY;


CREATE PROCEDURE getCombinations()
  BEGIN

    DECLARE countInt INT DEFAULT 0;
    DECLARE csv varchar(100);
    DECLARE region varchar(100);
    DECLARE v_last_row_fetched INT;
    declare v_counter int unsigned default 1;

    DECLARE counter cursor for
      select  * from ( select region as region,
                              count(distinct idString) as countInt,
                              group_concat(idString) as csv
                          from testing
                          group by region ) temp;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET  v_last_row_fetched=1;
    SET SESSION sql_mode = CONCAT(@@sql_mode, ',PIPES_AS_CONCAT');

    delete from result;
    open counter;
    c1_loop: loop
      fetch counter into region , countInt, csv ;


      IF  v_last_row_fetched=1 THEN LEAVE c1_loop; END IF;

      #DEBUG STATEMENT HERE - 6 values instead of two displayed for csv3
      select csv as csv3;
      LEAVE c1_loop;

    end loop c1_loop;
    close counter;

  END;

DELIMITER ;

CALL getCombinations();
SET SESSION sql_mode = CONCAT(@@sql_mode, ',PIPES_AS_CONCAT');

1 个答案:

答案 0 :(得分:1)

问题是你有一个名为Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged Try Dim IPs As String() = Data.GetComponentIPs(ComboBox1.Text) ComboBox2.Items.Add(New ComboItem(Of String)("Component A", IPs(0))) ComboBox2.Items.Add(New ComboItem(Of String)("Component B", IPs(1))) 'Guessing at the names here, since they aren't in the question ComboBox2.Items.Add(New ComboItem(Of String)("Machine 1", IPs(2))) ComboBox2.Items.Add(New ComboItem(Of String)("Machine 2", IPs(3))) Catch ex As MySqlException MessageBox.Show(ex.Message) End Try End Sub 的局部变量,这个变量在region而不是列中使用。所以就好像你写了GROUP BY region,所以所有东西都组合在一起。

更改GROUP BY null变量的名称,它将起作用。通常,避免使用与表列名称相同的变量,这通常会导致问题。