doushi6932
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
    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;
    
    点赞 评论

相关推荐