我正在创建类似于广告系统的东西。 例如,我想显示给定数据库表中的 5 个广告(5 条记录)。 所以我执行类似
SELECT * FROM mytable
ORDER BY view_counter ASC
LIMIT 5
好的,它有效。 但是,如何使用单个 SQL 上下文更新“view_counter”(即显示次数的计数器)? 而且,如果我不要求太多,是否可以保存我的记录被返回的“位置”? 比如我的sql返回
- record F (pos. 1)
- record X (pos. 2)
- record Z (pos. 3)
然后在字段“Avarage_Position”中保存位置的..平均值?
提前致谢。
问候
最佳答案
how can contextualy update the "view_counter" (that is a counter with the number of show) maybe with a single SQL ?
这通常是由分析/排名/窗口功能处理的,MySQL 目前不支持这些功能。但是您可以使用以下查询来获取您想要的输出:
SELECT *,
@rownum := @rownum + 1 AS rank
FROM mytable
JOIN (SELECT @rownum := 1) r
ORDER BY view_counter ASC
LIMIT 5
你会得到这样的输出:
description | rank
--------------------------
record F | 1
record X | 2
record Z | 3
if i don't ask too much, is it possible to save the "position" which my record are returned ?
我不建议这样做,因为这意味着每次发生变化时都需要更新数据。在其他数据库上,我建议使用 View ,以便仅在使用 View 时进行计算,但 MySQL 不支持在 View 中使用变量。
还有一种使用子选择获取排名值的替代方法 - this link is for SQL Server, but there's nothing in the solution that is SQL Server specific .
关于sql - 如何更新结果集的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3220456/