gpt4 book ai didi

postgresql - mysql的SQL_CALC_FOUND_ROWS在postgresql中有类似的功能吗?

转载 作者:行者123 更新时间:2023-11-29 11:31:30 27 4
gpt4 key购买 nike

用过mysql的都知道:

SELECT SQL_CALC_FOUND_ROWS ..... FROM table WHERE ...  LIMIT 5, 10;

在运行这个之后:

SELECT FOUND_ROWS();

我如何在 postrgesql 中执行此操作?到目前为止,我只找到了必须发送两次查询的方法...

最佳答案

不,没有(至少 not as of July 2007 )。恐怕你将不得不求助于:

BEGIN ISOLATION LEVEL SERIALIZABLE;

SELECT id, username, title, date FROM posts ORDER BY date DESC LIMIT 20;
SELECT count(id, username, title, date) AS total FROM posts;

END;

isolation level需要 SERIALIZABLE 以确保查询不会看到 SELECT 语句之间的并发更新。

不过,您还有另一种选择,即使用触发器对行进行INSERTed 或DELETEd 计数。假设您有下表:

CREATE TABLE posts (
id SERIAL PRIMARY KEY,
poster TEXT,
title TEXT,
time TIMESTAMPTZ DEFAULT now()
);

INSERT INTO posts (poster, title) VALUES ('Alice', 'Post 1');
INSERT INTO posts (poster, title) VALUES ('Bob', 'Post 2');
INSERT INTO posts (poster, title) VALUES ('Charlie', 'Post 3');

然后,执行以下操作创建一个名为 post_count 的表,其中包含 posts 中行数的运行计数:

-- Don't let any new posts be added while we're setting up the counter.
BEGIN;
LOCK TABLE posts;

-- Create and initialize our post_count table.
SELECT count(*) INTO TABLE post_count FROM posts;

-- Create the trigger function.
CREATE FUNCTION post_added_or_removed() RETURNS TRIGGER AS $$
BEGIN
IF TG_OP = 'DELETE' THEN
UPDATE post_count SET count = count - 1;
ELSIF TG_OP = 'INSERT' THEN
UPDATE post_count SET count = count + 1;
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;

-- Call the trigger function any time a row is inserted.
CREATE TRIGGER post_added_or_removed_tgr
AFTER INSERT OR DELETE
ON posts
FOR EACH ROW
EXECUTE PROCEDURE post_added_or_removed();

COMMIT;

请注意,这维护了 所有 posts 行的运行计数。要保持某些行的运行计数,您必须对其进行调整:

SELECT count(*) INTO TABLE post_count FROM posts WHERE poster <> 'Bob';

CREATE FUNCTION post_added_or_removed() RETURNS TRIGGER AS $$
BEGIN
-- The IF statements are nested because OR does not short circuit.
IF TG_OP = 'DELETE' THEN
IF OLD.poster <> 'Bob' THEN
UPDATE post_count SET count = count - 1;
END IF;
ELSIF TG_OP = 'INSERT' THEN
IF NEW.poster <> 'Bob' THEN
UPDATE post_count SET count = count + 1;
END IF;
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;

关于postgresql - mysql的SQL_CALC_FOUND_ROWS在postgresql中有类似的功能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3373233/

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