为COUNT查询连接表

时间:2014-01-19 16:12:35

标签: php mysql

我正在使用以下脚本来显示页面,其中$ URL与页面网址匹配(例如MySite/People/Carl_Sagan)...

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

switch($Total['num'])
{
 case 1:
 break;
 case 2:
 break;
 default:
 break;
}

在另一个网站上,我想将几​​张桌子连在一起,形成一种迷你百科全书。我知道如何使用UNION命令,但它不能使用此查询。请注意,表gz_life中的目标字段名为Taxon,而不是URL。我以为我可以用某种方式将它作为别名 - Taxon AS URL - 但这似乎也没有用。

$sql= "SELECT COUNT(URL) AS num FROM pox_topics WHERE URL = :url
UNION ALL
SELECT COUNT(URL) AS num FROM people WHERE URL = :url
UNION ALL
SELECT COUNT(Taxon) AS num FROM gz_life WHERE Taxon = :url";

有人能告诉我在PDO查询中将表连接在一起的最佳方法吗?

2 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点(如果我理解你想要实现的目标)。一个人会使用你已经拥有的东西,但最后一步是加起来计算:

SELECT SUM(num) FROM (
  SELECT COUNT(URL) AS num FROM pox_topics WHERE URL = :url
  UNION ALL
  SELECT COUNT(URL) AS num FROM people WHERE URL = :url
  UNION ALL
  SELECT COUNT(Taxon) AS num FROM gz_life WHERE Taxon = :url
) as subquery

请注意,您需要子查询的别名才能使查询正确。

答案 1 :(得分:0)

如果您可以在一行中使用计数,则可以编写一个仅使用:url一次的查询:

select tp.num_topic, tp.num_people, count(*) as num_taxon
from (select t.url, t.num_topic, count(*) as num_people
      from (SELECT t.url, COUNT(URL) AS num_topic
            from pox_topics t
            where t.URL = :url
           ) t join
           people p
           on t.url = p.url
    ) tp join
    gz_life gl
    on gl.Taxon = tp.url;

这会将:url转换为一列,然后使用连续的子查询层来计算计数。

编辑:

有些计数可能为0.要处理这种情况:

select tp.num_topic, tp.num_people, count(gl.taxon) as num_taxon
from (select t.url, t.num_topic, count(p.url) as num_people
      from (SELECT const.url, COUNT(t.URL) AS num_topic
            from (select :url as url) const left outer join
                 pox_topics t
                 on t.url = const.url
           ) t left outer join
           people p
           on t.url = p.url
    ) tp left outer join
    gz_life gl
    on gl.Taxon = tp.url;