简体   繁体   中英

MariaDB 10.0: Split 1 row into many based on column value

I have a table that looks something like this:

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

How can I query the database so that 1 row is shown per count? Ie like this:

| 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     |

In case it helps, I've created a DB fiddle: https://www.db-fiddle.com/f/wRZgBYkDM18c5fk7tgkBkA/0

Possibly SQL isn't the best option to solve in a simple way what you need, however, an alternative is to use stored procedures, cursors and a temporary table (the example is in MariaDB 10.3.9, but with some changes it will work in 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 ;

See dbfiddle .

The query below is ugly but works:

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

NOTE: it only returns correct data if the total number of records in your table is => max(count).

Original approach found in answer here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM