dqk94069 2014-01-19 16:12
浏览 58
已采纳

为COUNT查询连接表

I'm using the following script to display pages, where $URL matches a page URL (e.g. 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;
}

On another site, I want to join several tables together, forming sort of a mini-encyclopedia. I know how to use the UNION command, but it isn't working with this query. Note that the target field in the table gz_life is named Taxon, not URL. I thought I could somehow alias it - Taxon AS URL - but that doesn't seem to be working, either.

$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";

Can anyone tell me the best way to join tables together in a PDO query?

  • 写回答

2条回答 默认 最新

  • dtkyayvldeaqhl7151 2014-01-19 18:15
    关注

    There are a few ways to do this (if I understand what you're trying to achieve). One would be use what you already have, but do the last step to add up the counts:

    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
    

    Note that you will need the alias for the subquery to make the query correct.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块