简体   繁体   English

Postgresql 下单

[英]Postgresql order by out of order

I have a database where I need to retrieve the data as same order as it was populated in the table.我有一个数据库,我需要按照与表中填充的顺序相同的顺序检索数据。 The table name is bible When I type in table bible;表名是圣经当我输入table bible; in psql, it prints the data in the order it was populated with, but when I try to retrieve it, some rows are always out of order as in the below example:在 psql 中,它按填充顺序打印数据,但是当我尝试检索它时,某些行总是乱序的,如下例所示:

table bible

-[ RECORD 1 ]-----------------------------------------------------------------------------------------------------------------------------------------
id      | 1
day     | 1
book    | Genesis
chapter | 1
verse   | 1
text    | In the beginning God created the heavens and the earth.
link    | https://api.biblia.com/v1/bible/content/asv.txt.txt?passage=Genesis1.1&key=dc5e2d416f46150bf6ceb21d884b644f
-[ RECORD 2 ]-----------------------------------------------------------------------------------------------------------------------------------------
id      | 2
day     | 1
book    | John
chapter | 1
verse   | 1
text    | In the beginning was the Word, and the Word was with God, and the Word was God.
link    | https://api.biblia.com/v1/bible/content/asv.txt.txt?passage=John1.1&key=dc5e2d416f46150bf6ceb21d884b644f
-[ RECORD 3 ]-----------------------------------------------------------------------------------------------------------------------------------------
id      | 3
day     | 1
book    | John
chapter | 1
verse   | 2
text    | The same was in the beginning with God.
link    | https://api.biblia.com/v1/bible/content/asv.txt.txt?passage=John1.2&key=dc5e2d416f46150bf6ceb21d884b644f

Everything is in order, but when I try to query the same thing using for example: select * from bible where day='1' or select * from bible where day='1' order by day or select * from bible where day='1' order by day, id;一切都井井有条,但是当我尝试使用例如查询相同的东西时: select * from bible where day='1'select * from bible where day='1' order by day or select * from bible where day='1' order by day, id; , I always get some rows out of order either in the day selected (here 1) or any other day. ,我总是在所选日期(此处为 1)或任何其他日期出现一些乱序的行。 I have been using Django to interfere with Postgres database, but since I found this problem, I tried to query using SQL, but nothing, I still get rows out of order, although they all have unique ids which I verified with select count(distinct id), count(id) from bible; I have been using Django to interfere with Postgres database, but since I found this problem, I tried to query using SQL, but nothing, I still get rows out of order, although they all have unique ids which I verified with select count(distinct id), count(id) from bible;

- [ RECORD 1 ]------------------------------------------------------------------------------------------------------
id      | 1
day     | 1
book    | Genesis
chapter | 1
verse   | 1
text    | In the beginning God created the heavens and the earth.
link    | https://api.biblia.com/v1/bible/content/asv.txt.txt?passage=Genesis1.1&key=dc5e2d416f46150bf6ceb21d884b644f
-[ RECORD 2 ]-----------------------------------------------------------------------------------------------------------------------------------------
id      | 10
day     | 1
book    | Colossians
chapter | 1
verse   | 18
text    | And he is the head of the body, the church: who is the beginning, the firstborn from the dead; that in all things he might have the preemine
nce.
link    | https://api.biblia.com/v1/bible/content/asv.txt.txt?passage=Colossians1.18&key=dc5e2d416f46150bf6ceb21d884b644f
-[ RECORD 3 ]-----------------------------------------------------------------------------------------------------------------------------------------
id      | 11
day     | 1
book    | Genesis
chapter | 1
verse   | 2
text    | And the earth was waste and void; and darkness was upon the face of the deep: and the Spirit of God moved upon the face of the waters.
link    | https://api.biblia.com/v1/bible/content/asv.txt.txt?passage=Genesis1.2&key=dc5e2d416f46150bf6ceb21d884b644f

As you could see above if you notice, the ids are out of order 1, 10, 11.正如您在上面看到的,如果您注意到,ID 的顺序是 1、10、11。

my table我的桌子

                              Table "public.bible";
Column  | Type | Collation | Nullable | Default | Storage  | Stats target | Description 
---------+------+-----------+----------+---------+----------+--------------+-------------
id      | text |           |          |         | extended |              | 
day     | text |           |          |         | extended |              | 
book    | text |           |          |         | extended |              | 
chapter | text |           |          |         | extended |              | 
verse   | text |           |          |         | extended |              | 
text    | text |           |          |         | extended |              | 
link    | text |           |          |         | extended |              | 
Access method: heap

The id field is of type text because I used pandas's to_sql() method to populate the bible table. id 字段是文本类型,因为我使用 pandas 的to_sql()方法来填充圣经表。 I tried to drop the id column and then I added it again as a PK with ALTER TABLE bible ADD COLUMN id SERIAL PRIMARY KEY;我尝试删除 id 列,然后使用ALTER TABLE bible ADD COLUMN id SERIAL PRIMARY KEY; but I still get data return out of order.但我仍然让数据返回无序。

Is there anyway I can retrieve the data with ordering with id, without having some of the rows totally out of order?无论如何,我可以用 id 排序检索数据,而不会让某些行完全乱序吗? Thank you in advance!先感谢您!

Thou shalt cast thy id to integer to order it as number.您应将您的id转换为cast以将其作为编号订购。

SELECT * FROM bible ORDER BY cast(id AS integer);

While @jordanvrtanoski is correct, the way to do this is django is:虽然@jordanvrtanoski 是正确的,但这样做的方法是 django 是:

>>> Bible.objects.extra(select={'id': 'CAST(id AS INTEGER)'}).order_by('id').values('id')
<QuerySet [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 10}, {'id': 20}]>

Side note: If you want to filter on day as an example, you can do this:旁注:如果你想过滤day作为一个例子,你可以这样做:

>>> Bible.objects.extra(select={
    'id': 'CAST(id AS INTEGER)', 
    'day': 'CAST(day AS INTEGER)'}
).order_by('id').values('id', 'day').filter(day=2)
<QuerySet [{'id': 2, 'day': 2}, {'id': 10, 'day': 2}, {'id': 11, 'day': 2}, {'id': 20, 'day': 2}]>

Otherwise you get this issue: (notice 1 is followed by 10 and not 2 )否则你会得到这个问题:(注意1后跟10而不是2

>>> Bible.objects.order_by('id').values('id')
<QuerySet [{'id': '1'}, {'id': '10'}, {'id': '2'}, {'id': '20'}, {'id': '3'}]>

I HIGHLY suggest you DO NOT do any of this, and set your tables correctly (have the correct column types and not have everything as text ), or your query performance is going to suck.. BIG TIME我强烈建议您要这样做,并正确设置您的表(具有正确的列类型,而不是将所有内容都作为text ),否则您的查询性能会很糟糕......大时间

Building on both answers of @jordanvrtanoski and @Javier Buzzi, and some search online, the issue is because the ids are of type TEXT (or VARCHAR too), so, you would need to cast the id to type INTEGER as in the following:基于@jordanvrtanoski 和@Javier Buzzi 的两个答案以及一些在线搜索,问题是因为ID 是TEXT 类型(或VARCHAR 也是),因此,您需要将ID 转换为INTEGER 类型,如下所示:

ALTER TABLE bible ALTER COLUMN id TYPE integer USING (id::integer);

Now here is my table现在这是我的桌子

                                                Table "public.bible"
Column  |  Type   | Collation | Nullable |                 Default                 | Storage  | Stats target | Description 
---------+---------+-----------+----------+-----------------------------------------+----------+--------------+-------------
id      | integer |           |          | nextval('bible_id_seq'::regclass) | plain    |              | 
day     | text    |           |          |                                         | extended |              | 
book    | text    |           |          |                                         | extended |              | 
chapter | text    |           |          |                                         | extended |              | 
verse   | text    |           |          |                                         | extended |              | 
text    | text    |           |          |                                         | extended |              | 
link    | text    |           |          |                                         | extended |              | 
Indexes:
    "lesson_unique_id" UNIQUE CONSTRAINT, btree (id)
Referenced by:
    TABLE "notes_note" CONSTRAINT "notes_note_verse_id_5586a4bf_fk" FOREIGN KEY (verse_id) REFERENCES days_lesson(id) DEFERRABLE INITIALLY DEFERRED
Access method: heap

Hope this helps other people, and thank you everyone!希望这对其他人有帮助,谢谢大家!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM