dtdb99743
dtdb99743
2014-01-20 01:21
浏览 87
已采纳

子查询(COUNT)不起作用

I'm working with PHP and MySQL. This query works, where my page URL is MySite/Carl_Sagan (Carl_Sagan = $MyURL) and Carl_Sagan is also a value in a database table named people, field URL:

$sql= "SELECT COUNT(URL) AS num FROM people WHERE URL = :MyURL";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':MyURL',$MyURL,PDO::PARAM_STR);
$stmt->execute();
$Total = $stmt->fetch();

switch($Total['num'])
{
case 1:
echo "
";
require($BaseINC."/$MyPHP/inc/C/2_Child.php");
break;
case 0:
break;
default:
break;
}

But when I link several tables together through UNION ALL, turning it into a subquery, it doesn't work. I'm not getting any error messages, but the value for $Total['num'] is 0, when it should be 1.

Can anyone see the problem with my subquery, posted below?

 $sql = "SELECT SUM(num) FROM (
  SELECT COUNT(URL) AS num FROM pox_topics WHERE URL = :MyURL
  UNION ALL
  SELECT COUNT(URL) AS num FROM people WHERE URL = :MyURL
  UNION ALL
  SELECT 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();

I should note that the subquery doesn't work even if I strip it down to the original table, like this:

$sql = "SELECT SUM(num) FROM (
 SELECT COUNT(URL) AS num FROM people WHERE URL = :MyURL
) AS X";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':MyURL',$MyURL,PDO::PARAM_STR);
$stmt->execute();
$Total = $stmt->fetch();
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doukanhua0752
    doukanhua0752 2014-01-20 01:32
    已采纳

    There is no $Total['num'] anymore. Try SELECT SUM(num) AS num...

    点赞 评论

相关推荐