0

我有两个查询,必须在一个查询执行中执行。例如

$query1 = "SELECT COUNT(*) AS c1 FROM table WHERE condition1";
$query2 = "SELECT COUNT(*) AS c2 FROM table WHERE condition2";

$result = mysqli->query($query1 ." UNION ".$query2);

while($res = $result->fetch_assoc())
{
  print $res;
}

我必须将两个计数分别作为 c1 和 c1;

通过执行上面的代码,我得到了 {"c1":"number of counts"}

可能的解决方案是什么?

提前致谢。

4

6 回答 6

4

只需使用 CASE 语句:

SELECT 
SUM(
CASE WHEN condition1 
     THEN 1
     ELSE 0
END) AS c1,

SUM(
CASE WHEN condition2 
     THEN 1
     ELSE 0
END) AS c2,

FROM table 
于 2013-10-18T07:27:33.360 回答
1

使用UNION ALL代替UNION

$result = mysqli->query($query1 ." UNION ALL".$query2); 
于 2013-10-18T07:30:01.077 回答
1

更改sql查询

SELECT 
(SELECT COUNT(*) FROM table WHERE condition1) as c1,
(SELECT COUNT(*) FROM table WHERE condition2) as c2
FROM table
于 2013-10-18T07:35:28.823 回答
0

我有两个查询,必须在一个查询执行中执行。

不,你没有。

只需在 2 个单独的调用中运行它们。

于 2013-10-18T07:26:19.467 回答
0

尝试这样做以获得计数:

$count = 0;
while($res = $result->fetch_assoc())
{
  $count += array_sum($res);
}
于 2013-10-18T07:27:33.250 回答
0
SELECT count(*) count1, td2.count2
FROM table1 td1 
LEFT OUTER JOIN (SELECT table2_id, count(*) count2 FROM  table2 WHERE condition2 )td2
ON td2.table2_id = td1.table1_id
WHERE condition1
于 2013-10-18T11:02:31.610 回答