gpt4 book ai didi

php - 将 LIMIT 1 添加到 COUNT 查询

转载 作者:可可西里 更新时间:2023-11-01 07:52:04 26 4
gpt4 key购买 nike

这是我用来显示页面的 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

消除重复

这就是我现在正在使用的东西。

$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();

但是,我收到错误消息Unknown column X.SUM(或 X.URL 等)。

有人可以告诉我正确的方法吗?

最佳答案

使用如下查询,您将获得所需的输出:

 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

关于php - 将 LIMIT 1 添加到 COUNT 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32981754/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com