gpt4 book ai didi

php - SQL_CALC_FOUND_ROWS 返回错误

转载 作者:行者123 更新时间:2023-11-29 00:56:02 26 4
gpt4 key购买 nike

我使用嵌套的 MySQL 查询来获取用户帖子,当我将 SQL_CALC_FOUND_ROWS 放入子查询时,MySQL 返回错误:Incorrect usage/placement of 'SQL_CALC_FOUND_ROWS'

查询是:

SELECT inner_table.*
, users.username as last_username
, posts.date_added as last_date_added
, users.user_id as last_user_id
, posts.date_added as last_post_date
FROM (
SELECT SQL_CALC_FOUND_ROWS topics.topic_id
, topics.date_added
, topics.title
, topics.user_id
, MAX(posts.post_id) as last_post
, posts.user_id as post_user_id
, users.username
, topics.previews
, topics.fcat_id
, topics.is_important
, topics.is_locked
, topics.lastpost_time
, (SELECT COUNT(*) FROM posts WHERE posts.topic_id=topics.topic_id) as posts_cnt
FROM topics
LEFT JOIN users ON (users.user_id = topics.user_id)
LEFT JOIN posts ON (topics.topic_id = posts.topic_id)
WHERE topics.user_id = ".$this->session->getSession("user_data", "user_id")."
OR ".$this->session->getSession("user_data", "user_id")."
IN (
SELECT DISTINCT user_id
FROM posts
WHERE posts.topic_id = topics.topic_id
)
GROUP BY topics.topic_id
ORDER BY topics.lastpost_time DESC
LIMIT ".$limit * $page.", ".$limit."
) as inner_table
LEFT JOIN `posts` ON (posts.post_id=inner_table.last_post)
LEFT JOIN `users` ON (users.user_id=posts.user_id)
ORDER BY inner_table.lastpost_time DESC

最佳答案

我认为内部查询不允许使用 SQL_CALC_FOUND_ROWS
改为放入外部查询。

SELECT SQL_CALC_FOUND_ROWS inner_table.*
....

最后一行还有错误:

ORDER BY inner_table.lastpost_time DES

替换为:

ORDER BY inner_table.lastpost_time DESC

更新

为回应您的评论,我们提出了以下解决方法。

将内部选择输出到临时表中。

使用这样的代码:

/* do this once*/
CREATE TABLE `temp_table` LIKE SELECT topics.topic_id
, topics.date_added ....

/*do this for every query*/
DELETE FROM temp_table WHERE temp_table.topic_id <> 0;
INSERT INTO temp_table SELECT topics.topic_id
, topics.date_added
, topics.title
.... /*!! without the limit clause !!*/
SELECT count(*) as rowcount FROM temp_table;

/*then use the temp_table in place of the inner select*/

SELECT inner_table.*
, users.username as last_username
, posts.date_added as last_date_added
, users.user_id as last_user_id
, posts.date_added as last_post_date
FROM temp_table .....
LIMIT ....

使用 SQL_CALC_FOUND_ROWS 对 INSERT .. SELECT 也不起作用,但上面的代码是一种解决方法,您当然可以单独运行内部查询并在其上添加 LIMIT 1尽可能快。

关于php - SQL_CALC_FOUND_ROWS 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6083322/

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