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 有卷积神经网络识别害虫的项目吗
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件