子查询(COUNT)不起作用

时间:2014-01-20 01:21:57

标签: php mysql

我正在使用PHP和MySQL。此查询有效,我的页面网址为MySite / Carl_Sagan(Carl_Sagan = $ MyURL),而Carl_Sagan也是名为people的数据库表中的值,字段网址:

$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 "\n";
require($BaseINC."/$MyPHP/inc/C/2_Child.php");
break;
case 0:
break;
default:
break;
}

但是,当我通过UNION ALL将几个表链接在一起时,将其转换为子查询,它不起作用。我没有收到任何错误消息,但是$ Total ['num']的值是0,它应该是1。

任何人都可以看到我的子查询出现问题,在下面发布了吗?

 $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();

我应该注意,即使我将它删除到原始表,子查询也不起作用,如下所示:

$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 个答案:

答案 0 :(得分:1)

不再有$Total['num']了。试试SELECT SUM(num) AS num ...