I have a table with columns
object varchar(255),
frequency tinyint(3) unsigned,
I want to concatenate the objects if the sum of frequencies reach a value. Currently I am doing this in PHP
as
.. query loop {
$object .= $row['object'].",";
$frequency = $frequency+$row['frequency'];
if($frequency > 20) { // 20 is a given value
$mysqli->query("INSERT INTO table2 (concatenated_column) VALUES ('$object')");
$frequency=0;
$object='';
}
}
Is it possible to do this with a native query of mysql instead of bringing the data into PHP and returning back to mysql?
Since the process is simple, I think mysql has enough functions to do so, but I do not know how to do so.
In fact, I want to group concatenate the entire column and split it when sum of frequency
reaches the given value (i.e. 20). This needs a loop of INSERT
s in which the sum of frequency
reset to 0 upon reaching 20.
UPDATE: The process with do as:
table1:
object frequency
object1 7
object2 5
object3 6
object4 8
object5 2
table2:
concatenated_column
object1,object2,object3,object4
object5,....
Best Answer
Basically, you want to result the running total and group it
This requires iterative variable manipulation.
First, your sample data quadrupled:
Let's make the query that generates group values:
Would you believe it works?
First I'll let you see the inner subquery's output
Look at the
cc
column. It increments every time the sum exceeds @freq_limit (20) and resets.Now just run GROUP_CONCAT on object, grouping by
cc
Just set @freq_limit to whatever value you need.
To show it works for just the 5 rows you supplied:
Give it a Try !!!