这是我用来显示网页的COUNT个查询:
$sql = "
SELECT SUM(num) as num FROM (
SELECT
COUNT(URL) AS num
, 'World' AS GoSection
, 'GW' AS MySite
FROM gw_geog
WHERE URL = :MyURL AND G1 = 1
UNION ALL
SELECT
COUNT(URL) AS num
, 'World' AS GoSection
, 'GW' AS MySite
FROM gw_geog_political
WHERE URL = :MyURL
) AS X";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':MyURL',$MyURL,PDO::PARAM_STR);
$stmt->execute();
$Total = $stmt->fetch();
我想做两处修改:
1)从每一行删除 WHERE URL =:MyURL ,并将其合并到查询末尾的单行中
2)通过添加 LIMIT 1
来重复Zap这就是我现在正在使用的。
$sql = "SELECT SUM(num) as num FROM (
SELECT COUNT(URL) AS num, 'World' AS GoSection, 'GW' AS MySite FROM gw_geog WHERE URL = :MyURL AND G1 = 1
UNION ALL
SELECT COUNT(URL) AS num, 'World' AS GoSection, 'GW' AS MySite FROM gw_geog_political WHERE URL = :MyURL
) AS X
WHERE X.URL LIKE :MyURL LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':MyURL',$MyURL,PDO::PARAM_STR);
$stmt->execute();
$Total = $stmt->fetch();
但是,我收到错误消息未知列X.SUM (或X.URL等)。
有人能告诉我这样做的正确方法吗?
答案 0 :(得分:6)
使用Query As Follows,您将获得所需的输出:
SELECT
SUM(num) AS num
FROM
(
SELECT
COUNT(URL) AS num,
'World' AS GoSection,
'GW' AS MySite,
gw_geog.`URL` as URL
FROM
gw_geog
WHERE
URL = :MyURL
AND G1 = 1
UNION ALL
SELECT
COUNT(URL) AS num,
'World' AS GoSection,
'GW' AS MySite,
gw_geog_political.`URL` as URL
FROM
gw_geog_political
WHERE
URL = :MyURL
) AS X
WHERE
X.URL like :MyURL
LIMIT 1
答案 1 :(得分:1)
如果我了解你,limit 1
并不是你想要的。
这是一个小提琴:http://sqlfiddle.com/#!9/5ffbd/5
SELECT count(URL) AS num
,'World' AS GoSection
,'GW' AS MySite
FROM (
SELECT URL
,G1
,'a' AS tbl
FROM gw_geog
UNION ALL
SELECT URL
,G1
,'b' AS tbl
FROM gw_geog
) a
WHERE a.tbl = 'b'
OR (
a.tbl = 'a'
AND a.G1 = 1
)
AND a.URL = :MyURL