2017-04-14 32 views
0

使用PostgreSQL 9.4查詢時,我有一個表是這樣的:重用使用它的操作上LIMIT和OFFSET PostgreSQL的

CREATE TABLE products 
AS 
    SELECT id::uuid, title, kind, created_at 
    FROM (VALUES 
    ('61c5292d-41f3-4e86-861a-dfb5d8225c8e', 'foo', 'standard' , '2017/04/01'), 
    ('def1d3f9-3e55-4d1b-9b42-610d5a46631a', 'bar', 'standard' , '2017/04/02'), 
    ('cc1982ab-c3ee-4196-be01-c53e81b53854', 'qwe', 'standard' , '2017/04/03'), 
    ('919c03b5-5508-4a01-a97b-da9de0501f46', 'wqe', 'standard' , '2017/04/04'), 
    ('b3d081a3-dd7c-457f-987e-5128fb93ce13', 'tyu', 'other' , '2017/04/05'), 
    ('c6e9e647-e1b4-4f04-b48a-a4229a09eb64', 'ert', 'irregular', '2017/04/06') 
) AS t(id,title,kind,created_at); 

需要將數據分割成n大小相同的部件。如果這個表有一個正規的id會更容易,但既然它有uuid那麼我不能使用modulo操作(據我所知)。

到目前爲止,我這樣做:

SELECT * FROM products 
WHERE kind = 'standard' 
ORDER BY created_at 
LIMIT(
    SELECT count(*) 
    FROM products 
    WHERE kind = 'standard' 
)/2 
OFFSET(
    (
    SELECT count(*) 
    FROM products 
    WHERE kind = 'standard' 
)/2 
)*1; 

工作正常,但做同樣的查詢3次,我不認爲這是一個好主意,在count不是「貴」,但每次有人想要修改/更新查詢將需要在3個部分中完成。目前n設置爲2和偏移

注意設置爲1但兩者可以採用其他值。也限制下舍入,所以可能會有一個缺失值,我可以用其他方法修復它,但在查詢時它會很好。

你可以看到的例子here

回答

1

只是爲了打消你永遠不能使用串行和模量獲得的部分,因爲串行不能保證是無間隙的一個神話。雖然你可以使用row_number()

SELECT row_number() OVER() % 3 AS parts, * FROM products; 
parts |     id     | title | kind | created_at 
-------+--------------------------------------+-------+-----------+------------ 
    1 | 61c5292d-41f3-4e86-861a-dfb5d8225c8e | foo | standard | 2017/04/01 
    2 | def1d3f9-3e55-4d1b-9b42-610d5a46631a | bar | standard | 2017/04/02 
    0 | cc1982ab-c3ee-4196-be01-c53e81b53854 | qwe | standard | 2017/04/03 
    1 | 919c03b5-5508-4a01-a97b-da9de0501f46 | wqe | standard | 2017/04/04 
    2 | b3d081a3-dd7c-457f-987e-5128fb93ce13 | tyu | other  | 2017/04/05 
    0 | c6e9e647-e1b4-4f04-b48a-a4229a09eb64 | ert | irregular | 2017/04/06 
(6 rows) 

這將不會得到相同的部分,除非部分進入平等計數。

相關問題