我被相当简单的查询困住了!
简单地说,我已经创建了一个搜索(过滤器)面板,现在我正在添加分页。
我在返回当前查询中的行数方面遇到问题,主要取决于动态更改$detailed_search_query
变量。
我需要进行以下工作,并正确添加COUNT(),因此新行总数将包含unique_id
的总数。
当前SQL:
$sql = $db->prepare( "
SELECT
individuals.individual_id,
individuals.unique_id,
individuals.fullname,
individuals.day_of_birth,
TIMESTAMPDIFF(YEAR,individuals.day_of_birth,CURDATE()) AS age,
individuals.gender,
individuals.record_timestamp,
individuals.active,
individuals.deleted,
individuals_dynamics.weight,
individuals_dynamics.degree,
individuals_dynamics.trainer_name
FROM
individuals as individuals
LEFT JOIN
individuals_dynamics AS individuals_dynamics ON individuals.unique_id = individuals_dynamics.individual_id
WHERE
$detailed_search_query $display recognized = 'yes'
GROUP BY
individuals.record_timestamp
ORDER BY $by $how
LIMIT " . $limit);
如果我向其添加COUNT(),则表示有Fatal error: Call to a member function execute() on a non-object
这是我的新查询(刚开始,休息是一样的)的样子,它返回上面的错误:
$sql = $db->prepare( "
SELECT
COUNT(individuals.unique_id),
individuals.individual_id,
individuals.unique_id,
individuals.fullname,
individuals.day_of_birth,
我在这里缺少什么?
我如何使用COUNT()的示例产生了有效的简单预查询:
$sql = $db->prepare("SELECT count(unique_id) FROM individuals");
$sql->execute();
$total = $sql->fetchColumn();
$pagination = new Pagination($paginate_number);
$limit = $pagination->getLimit($total);
是的,对,当我添加别名时,返回相同的错误,例如:
$sql = $db->prepare( "
SELECT
COUNT(individuals.unique_id) as total,
individuals.individual_id,
这是我最后一次编辑的不好,如果你添加别名,比如总计,那么查询工作但它只有COUNTS当前行并返回1但我需要总行数,例如:
Array
(
[0] => Array
(
[total] => 1
[0] => 1
[individual_id] => 51
[1] => 51
[unique_id] => f598edae
[2] => f598edae
当替换PHP变量时,我在WHERE子句中有类似的东西:
WHERE
individuals.fullname LIKE '%adam%' AND individuals_dynamics.degree BETWEEN '1' AND '3' AND EXTRACT(YEAR FROM (FROM_DAYS(DATEDIFF(NOW(),individuals.day_of_birth))))+0 BETWEEN '7' AND '10' AND individuals_dynamics.weight BETWEEN '20' AND '40' AND individuals_dynamics.degree BETWEEN '7' AND '10' AND deleted != 'yes' AND active != 'no' AND recognized = 'yes'
GROUP BY
individuals.record_timestamp
期望的结果是在最终数组中包含键总数,它表示基于动态PHP变量在当前查询中提取的结果总量,$detailed_search_query
和{{1} }:
现在我总共有1个。什么时候应该是75:
$display
答案 0 :(得分:4)
您获得的错误意味着PDO无法准备查询,原因是您的SQL查询中存在错误而数据库服务器无法执行它...所以要更好地理解问题你应该发布你试图直接在mysql客户端上执行查询的错误。
要实现所需的结果集,可以插入一个子查询,用于计算与外部查询具有相同individual_id
的记录。
在查询的第一部分之后:
SELECT
(SELECT COUNT(unique_id) FROM individuals i2 WHERE i2.individual_id = individuals. individual_id) AS total,
individuals.individual_id,
individuals.unique_id,
individuals.fullname,
individuals.day_of_birth,
请记住,要从子查询中正确引用外部查询的列,您应该使用两个不同的别名,即使您在两个查询(外部和子)中从同一个表中进行选择。