sqlalchemy:查询结果的顺序意外

编程入门 行业动态 更新时间:2024-10-22 17:29:08
本文介绍了sqlalchemy:查询结果的顺序意外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在 MySQL 中使用 SQLAlchemy 并且有一个带有两个外键的表:

I'm using SQLAlchemy with MySQL and have a table with two foreign keys:

class CampaignCreativeLink(db.Model): __tablename__ = 'campaign_creative_links' campaign_id = db.Column(db.Integer, db.ForeignKey('campaigns.id'), primary_key=True) creative_id = db.Column(db.Integer, db.ForeignKey('creatives.id'), primary_key=True)

然后我使用 for 循环将 3 个项目插入表中,如下所示:

Then I use a for loop to insert 3 items into the table like this:

session.add(8, 3) session.add(8, 2) session.add(8, 1)

但是当我检查表格时,项目的顺序是相反的

But when I checked the table, the items are ordered reversely

8 1 8 2 8 3

并且查询也反向显示顺序.这是什么原因,我如何才能保持添加顺序的顺序?

And the query shows the order reversely too. What's the reason for this and how can I keep the order same as when they were added?

推荐答案

表是一组的行,因此不保证有任何顺序,除非您指定 ORDER BY.

A table is a set of rows and are therefore not guaranteed to have any order unless you specify ORDER BY.

在 MySQL (InnoDB) 中,主键充当聚集索引.这意味着行以主键指定的顺序物理存储,在本例中为 (campaign_id, created_id),与插入顺序无关.如果您不指定 ORDER BY,这通常是返回行的顺序.

In MySQL (InnoDB), the primary key acts as the clustered index. This means that the rows are physically stored in the order specified by the primary key, in this case (campaign_id, created_id), regardless of the order of insertion. This is usually the order the rows are returned in if you don't specify an ORDER BY.

如果您需要按特定顺序返回行,请在查询时指定ORDER BY.

If you need your rows returned in a certain order, specify ORDER BY when you query.

更多推荐

sqlalchemy:查询结果的顺序意外

本文发布于:2023-10-25 22:06:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528245.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:查询结果   顺序   意外   sqlalchemy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!