如何让 MySQL 数据库中的一列成为其他列的函数?

发布于 2024-07-29 23:55:43 字数 85 浏览 3 评论 0原文

我正在使用一个数据库来跟踪读者在书中的位置。 我通过页数列和当前页列来做到这一点。

有没有办法添加等于(当前页/页数)的“进度”列?

I'm working with a database that keeps track of where a reader is in a book. I do this by having a page count column and a current page column.

Is there a way to add a 'progress' column that would be equal to (currentpage/pagecount)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

∝单色的世界 2024-08-05 23:55:43

你有两个选择。 您可以在 SELECT 上创建该字段:

SELECT book_id, user_id, (currentpage/pagecount) AS progress FROM user_books;

或者创建一个 VIEW,这将允许您在不明确说明操作的情况下查询它:

CREATE VIEW user_books_progress AS
  (SELECT book_id, user_id, (currentpage/pagecount) AS progress FROM user_books);

然后您可以将视图作为普通表:

SELECT book_id, user_id, progress FROM user_books_progress;

有关算术运算符和视图的更多信息可在文档中找到:

11.5.1:算术运算符
12.1.12。 创建视图语法

You have two options. You can either create that field on SELECT:

SELECT book_id, user_id, (currentpage/pagecount) AS progress FROM user_books;

Or create a VIEW, which will allow you to query it without explicitly stating the operation:

CREATE VIEW user_books_progress AS
  (SELECT book_id, user_id, (currentpage/pagecount) AS progress FROM user_books);

Then you can just query your view as a normal table:

SELECT book_id, user_id, progress FROM user_books_progress;

More information about Arithmetic Operators and Views are available in the documentation:

11.5.1: Arithmetic Operators
12.1.12. CREATE VIEW Syntax

杯别 2024-08-05 23:55:43

您不能将列定义为函数。 至少有两种解决方法:

  • 使用 BEFORE UPDATE 触发器更新进度列,您还需要一个 BEFORE INSERT 触发器。
  • 使用为您计算进度列的视图。

You cannot define a column to be a function. There are at least two workarounds to this:

  • Update your progress column using a BEFORE UPDATE trigger, you'll need one for BEFORE INSERT as well.
  • Use a view that calculates the progress column for you.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文