Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 获取两种类型的行数,行数最少_Php_Mysql - Fatal编程技术网

Php 获取两种类型的行数,行数最少

Php 获取两种类型的行数,行数最少,php,mysql,Php,Mysql,我有以下疑问 $sql = "SELECT customer FROM furniture WHERE id = :id AND category = :cat"; $stmt = $connectdb->prepare($sql); $stmt->execute(array(':id'=>$id, ':cat'=>"1")); $resulta = $stmt->fetchAll(PDO::FETCH_ASSOC); $rowcount = count($resu

我有以下疑问

$sql = "SELECT customer FROM furniture WHERE id = :id AND category = :cat";
$stmt = $connectdb->prepare($sql);
$stmt->execute(array(':id'=>$id, ':cat'=>"1"));
$resulta = $stmt->fetchAll(PDO::FETCH_ASSOC);
$rowcount = count($result);

这很好用。但是我需要从
中获取行数,其中id=:id和category=:cat
以及从
中获取行数,其中category=:cat
。是否可以在不必两次写入所有这些SELECT查询行的情况下同时执行这两项操作?

您可以使用条件求和来获得两个不同的计数

select 
sum(id = :id AND category = :cat) as count1,
sum(category = :cat) as count2
from furniture;
稍后,您只需获取记录并获取
count1
count2


注意:如果只进行行计数,它将始终返回1,因为它使用聚合函数

select sum(id = :id) as numCatId, count(*) as numCat
from furniture
where cat = :cat;

将条件放在
where
子句中允许MySQL在
furniture(cat)
(或者更好的
furniture(cat,id)上使用索引)
。一般来说,最好在
where
子句中加入常用的筛选条件。这样可以减少处理其余查询所需的行数。

这里的
id
是什么?PK?如果需要对
category
字段进行计数,则必须根据
customer
或任何其他字段进行查找d在桌子上。