我有两个查询,必须在一次查询执行中执行。例如
$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”:“计数数量”}
可能的解决办法是什么?
提前致谢。
答案 0 :(得分: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
答案 1 :(得分:1)
使用UNION ALL
代替UNION
:
$result = mysqli->query($query1 ." UNION ALL".$query2);
答案 2 :(得分:1)
更改sql查询
SELECT
(SELECT COUNT(*) FROM table WHERE condition1) as c1,
(SELECT COUNT(*) FROM table WHERE condition2) as c2
FROM table
答案 3 :(得分:0)
我有两个查询,必须在一次查询执行中执行。
不,你没有。
只需在两个不同的电话中运行它们。
答案 4 :(得分:0)
尝试这样做以获得计数:
$count = 0;
while($res = $result->fetch_assoc())
{
$count += array_sum($res);
}
答案 5 :(得分: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