优化MySQL操作以获得计数

时间:2014-02-17 18:36:35

标签: mysql optimization

我有这段可爱的代码可以复制不同的行数,因此我可以建立一个关联列表,列出公民拥有的每种商品的数量。

$citizen_id = 1;
$goods = array();
$goods_result = mysql_query("SELECT id,name FROM goods");
while(($goods_row = mysql_fetch_assoc($goods_result))) {
    $good_id = $goods_row['id'];
    $query = "SELECT count(*) FROM possessions where citizen_id=$citizen_id and good_id=$good_id";
    $possessed_result = mysql_query($query);
    $possessed_row = mysql_fetch_row($possessed_result);
    if($possessed_row) {
        $possessed = $possessed_row[0];
        $goods[$goods_row['name']] = $possessed;
    }
}
echo json_encode ($goods);

它有效,但运行速度太慢。在我看来,必须有一种方法让MySQL建立一个计数表并在一个查询中将它返回给我,但我不知道如何弄清楚如何做到这一点。关于如何加快这项操作的任何想法?

1 个答案:

答案 0 :(得分:2)

如何使用

之类的查询
SELECT  g.id good_id,
        count(*) cnt_of_goods
FROM    possessions p INNER JOIN
        goods g ON  p.good_id = g.id
where   citizen_id=$citizen_id 
GROUP BY    g.id