如何使用带COUNT查询的while循环?在下面的一系列子查询中,我为每个表分配了一个静态值(例如'PX'AS MySite2,'GZ'AS MySite2)......
$sql = "SELECT SUM(num) as num FROM (
SELECT 'PX' AS MySite2, COUNT(URL) AS num FROM pox_topics WHERE URL = :MyURL
UNION ALL
SELECT 'PX' AS MySite2, COUNT(URL) AS num FROM people WHERE URL = :MyURL
UNION ALL
SELECT 'GZ' AS MySite2, COUNT(Taxon) AS num FROM gz_life WHERE Taxon = :MyURL
) AS X";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':MyURL',$MyURL,PDO::PARAM_STR);
$stmt->execute();
$Total = $stmt->fetch();
要将MySite2转换为变量($ MySite2),我只需将其置于while循环中......
while ($row = $stmt->fetch())
{
$MySite2 = $row['MySite2'];
}
switch($Total['num'])
{
case 1:
但它不起作用。我可能只需要修改while ($row = $stmt->fetch())
,但我还没有找到合适的替代方案。另一种可能性是while循环不适用于COUNT个查询。无论哪种方式,有人能告诉我解决方案是什么吗?
答案 0 :(得分:2)
我认为您的查询不会返回MySite2列。 试试这个查询。
SELECT x.MySite2, SUM(num) as num FROM (
SELECT 'PX' AS MySite2, COUNT(URL) AS num FROM pox_topics WHERE URL = :MyURL
UNION ALL
SELECT 'PX' AS MySite2, COUNT(URL) AS num FROM people WHERE URL = :MyURL
UNION ALL
SELECT 'GZ' AS MySite2, COUNT(Taxon) AS num FROM gz_life WHERE Taxon = :MyURL
) AS X group by x.MySite2
答案 1 :(得分:2)
这就是我认为你想要实现的目标......
$sql = "SELECT 'PX' AS MySite2, COUNT(URL) AS num FROM pox_topics WHERE URL = :MyURL
UNION ALL
SELECT 'PX' AS MySite2, COUNT(URL) AS num FROM people WHERE URL = :MyURL
UNION ALL
SELECT 'GZ' AS MySite2, COUNT(Taxon) AS num FROM gz_life WHERE Taxon = :MyURL";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':MyURL',$MyURL,PDO::PARAM_STR);
$MySite2 = array();
$stmt->execute();
while ($row = $stmt->fetch())
{
$MySite2[] = array("mysite" => $row['MySite2'], "num" => $row['num']);
}
然后,您可以轻松地总结或以其他方式计算您想要的任何内容
答案 2 :(得分:0)
也许你应该改变“$ MySite2 = $ row ['MySite2'];” “$ MySite2 = $ row ['X'];”
由于整个查询都以名为“X”的列返回。
返回的唯一其他列是'num',
$ row ['MySite2']不会产生值,因为没有返回名为'MySite2'的列。
希望这有帮助。
答案 3 :(得分:0)
Mods:我不知道是否应该将其作为答案发布,但实际上并非如此;这更像是一种解决方法。所以随意将其从“答案”更改为任何内容。或者,如果我更容易做到这一点,请告诉我,我会将其删除并发布为评论等。
此页面上有很多很棒的提示,我会将其作为参考书签。 ;)