doushi6932 2014-01-20 02:29
浏览 24
已采纳

在COUNT查询上传递静态值(PHP / MySQL)

I have a series of queries for various sections and websites (e.g. MySite/World, MySite2/World, MySite3/People). It's actually two series of queries - COUNT queries that display pages and more complex queries that retrieve information from my database.

I'm now merging these projects into a single mini encyclopedia on a new website. The query below is from a different, but related, project, but it illustrates what I'm trying to do. Notice that I gave data from each table its own identity with 'GW' AS Site, 'GZ' AS Site, etc.

$stm = $pdo->prepare("SELECT 'GW' AS Site, CGW.N, CGW.URL, CGW.Date, CGW.Year, CGW.Brief
FROM calendar_gw CGW
WHERE CGW.URL = :MyURL
UNION ALL
SELECT 'GZ' AS Site, CGZ.N, CGZ.URL, CGZ.Date, CGZ.Year, CGZ.Brief
FROM calendar_gz CGZ
WHERE CGZ.URL = :MyURL
ORDER BY Year");
$stm->execute(array(
'MyURL'=>$MyURL
));

Now I'd like to know if there's a way to similarly give an ID to multiple tables in a COUNT query, like this one:

$sql = "SELECT SUM(num) as 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";

I actually want to give each subquery TWO ID's - website and section. For example, the values for the middle query should be $Site = 'PX', $Section = 'People'.

I've tried the obvious solutions, like...

SELECT 'PX' AS Site COUNT(URL) AS num FROM people WHERE URL = :MyURL

SELECT COUNT(URL) AS num 'PX' AS Site FROM people WHERE URL = :MyURL

SELECT COUNT(URL) AS num FROM 'PX' AS Site people WHERE URL = :MyURL

But nothing works so far. My ultimate goal would probably look something like this:

SELECT COUNT(URL) AS num FROM people ('PX' AS Site 'People' AS Section) WHERE URL = :MyURL

Can someone either show me the proper syntax or tell me if it's impossible to pass static values on a COUNT query? If what I'm trying to do is impossible, then I assume the only solution is to create a second, intermediate subquery designed only to pass static values.

  • 写回答

1条回答 默认 最新

  • dongyan3018 2014-01-20 02:32
    关注

    Your first version is fine, almost. It just needs a comma:

    SELECT 'PX' AS Site, COUNT(URL) AS num
    FROM people
    WHERE URL = :MyURL;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗