MariaDB 10.0:根据列值将1行分成多行

时间:2018-11-01 22:53:51

标签: mysql mariadb

我有一个看起来像这样的表:

| id  | item   | count |
| --- | ------ | ----- |
| 1   | item a | 3     |
| 2   | item b | 2     |
| 3   | item c | 4     |

如何查询数据库,以便每个计数显示1行?即像这样:

| id  | item   | count |
| --- | ------ | ----- |
| 1   | item a | 3     |
| 1   | item a | 3     |
| 1   | item a | 3     |
| 2   | item b | 2     |
| 2   | item b | 2     |
| 3   | item c | 4     |
| 3   | item c | 4     |
| 3   | item c | 4     |
| 3   | item c | 4     |

如果有帮助,我创建了一个数据库提琴:https://www.db-fiddle.com/f/wRZgBYkDM18c5fk7tgkBkA/0

2 个答案:

答案 0 :(得分:0)

SQL并非以简单的方式解决您所需的最佳选择,但是,替代方法是使用存储过程,游标和临时表(该示例在MariaDB 10.3.9中,但进行了一些更改)它将在MariaDB 10.0中工作):

DELIMITER //

CREATE PROCEDURE `sp_test`()
BEGIN
  CREATE TEMPORARY TABLE IF NOT EXISTS `temp_items`
  SELECT `id`, `item`, `count`
  FROM `items`
  LIMIT 0;

  FOR `repeat_row` IN (
    SELECT `id`, `item`, `count`
    FROM `items`
  ) DO
    FOR `current` IN 1..`repeat_row`.`count`
      DO
      INSERT INTO `temp_items`
      SELECT
        `repeat_row`.`id`,
        `repeat_row`.`item`,
        `repeat_row`.`count`;
    END FOR;
  END FOR;

  SELECT `id`, `item`, `count`
  FROM `temp_items`;
  DROP TEMPORARY TABLE IF EXISTS `temp_items`;
END//

DELIMITER ;

请参见dbfiddle

答案 1 :(得分:0)

下面的查询很难看,但是可以正常工作

SELECT id, item, count 
FROM (
   SELECT @curRow := @curRow + 1 AS row_number FROM mytable 
   INNER JOIN (SELECT @curRow := 0) AS ROW 
   ON @curRow < (SELECT max(count) from mytable) 
) AS B LEFT JOIN mytable C ON B.row_number <= C.count

注意:仅当表中的记录总数为=> max(count)时,它才会返回正确的数据。

answer here中找到的原始方法