ThinkPHP查询方式
1.子查询:buildSql()
参考http://document.thinkphp.cn/manual_3_2.html#sub_query
buildSql()方法 不进行实际的查询操作,只生成该次的SQL语句
例如:有三张表:
物资表material(id,名称,编号)
仓库表warehouse(id,名称)
库存表stock(id,仓库id,物资id,库存数量total)
查询:查询库存表,并且根据仓库id和物资code分组,查询总共有多少组
<? php
//1.实例化类
$model = M('Stock');
//2.查询字段
$field = "stock.id as id,warehouse.name as warehousename, material.code as code,material.title ";
//3.子查询
$subQuery= $model->alias('stock')
->join("LEFT JOIN __WAREHOUSE__ warehouse ON stock.warehouseid=warehouse.id")
->join("LEFT JOIN __MATERIAL__ material ON stock.materialid = material.id")
->field($field)
->group("warehouse.id,material.code")->buildSql();
//echo($subQuery); //输出sql 调试用
//4.外层查询
$totalarray = $model->alias('stock')
->query("select count(1) as total from". $subQuery."as childsql");
//5.符合条件的记录总数
$total=$totalarray[0]["total"];
?>
实现上述要求(分组的组数)也可以不用子查询,可以用select查询出分组后的所有记录,记录条数就是分组的组数