MySQL SELECT GROUP BY

时间:2016-07-20 20:22:15

标签: php mysql

如何从table_order中选择id,total并创建id列表,按add_by总计相应/ group?然后根据add_by将id和total的总和插入table_bill。这就是我到目前为止。

var url = window.location.href.split("/")

if(url(url.length-1) == 'news'){

    var d = document.getElementById("news"); //you need to add id 'news' to your news anchor tag
    d.className += " activemenu";

}

例如来自table_order的数据:(id | total | add_by)

//get unpaid orders
$sql = mysql_query("SELECT id,total,add_by FROM `order` WHERE status = '1'");
$res = mysql_num_rows($sql);

if($res>=1){
$tot = 0;
$ids = '';
while($row = mysql_fetch_array($sql)){
$ids .= $row['id'].",";
$tot += $row['total'];
$uid = $row['add_by'];
}
$ids = rtrim($ids, ",");

/*echo "<br>List of ID: ".$ids;
echo "<br>Total: ".$tot."<br>";
echo "<br>Add by: ".$uid."<br>";*/

//create bill
$sql_bill = "INSERT INTO `bill` (list,amount,user)  VALUES('$ids','$tot','$uid')";
$query = mysql_query($sql_bill);
}

然后插入table_bill :( list | amount | user)

103 | 350 | 4
104 | 450 | 6
105 | 250 | 6
106 | 400 | 4

1 个答案:

答案 0 :(得分:1)

获取结果的查询应该是

select group_concat(id) ,sum(total) ,add_by
from `order`
group by add_by

然后您可以使用单个查询命令

insert into table_bill (list , amount , user)
select group_concat(id) ,sum(total) ,add_by
from `order`
group by add_by