创建一个返回具有最新日期的不同 ID 的视图
我正在尝试构建一个包含 user_id、日期和统计值的视图,但遇到了问题。
本质上,如果我有一个表包含:
ID Stat Date
--------------------
01 AAA 01/01/2010
02 BBB 02/02/2010
03 CCC 05/01/2010
03 DDD 06/01/2010
01 EEE 07/01/2010
我的视图应该有:
ID Stat Date
--------------------
02 BBB 02/02/2010
03 DDD 06/01/2010
01 EEE 07/01/2010
我环顾四周,发现这个查询可以工作:
SELECT *
FROM (SELECT *
FROM TABLE
ORDER BY DATE DESC) tmp
GROUP BY ID
现在的问题是,我似乎不能在 MYSQL 的视图中执行子查询。
我尝试将其拆分为两个视图,第一个视图如下所示:
CREATE OR REPLACE VIEW VIEW_TEMP AS
SELECT *
FROM TABLE
ORDER BY DATE DESC
第二个视图:
CREATE OR REPLACE VIEW NEW_VIEW AS
SELECT *
FROM VIEW_TEMP
GROUP BY ID
问题是,虽然第一个视图返回与子查询相同的结果,但第二个视图给出了错误的日期值。
I'm trying to build a view that has contains user_id, date, and a statistics value, but I'm running into an issue.
Essentially if I have a table that contains:
ID Stat Date
--------------------
01 AAA 01/01/2010
02 BBB 02/02/2010
03 CCC 05/01/2010
03 DDD 06/01/2010
01 EEE 07/01/2010
My view should have:
ID Stat Date
--------------------
02 BBB 02/02/2010
03 DDD 06/01/2010
01 EEE 07/01/2010
I've looked around and I found that this query would work:
SELECT *
FROM (SELECT *
FROM TABLE
ORDER BY DATE DESC) tmp
GROUP BY ID
Now the problem is that it doesn't seem like I can do subqueries in views in MYSQL.
I've tried splitting it into two views, the first one like this:
CREATE OR REPLACE VIEW VIEW_TEMP AS
SELECT *
FROM TABLE
ORDER BY DATE DESC
and the second:
CREATE OR REPLACE VIEW NEW_VIEW AS
SELECT *
FROM VIEW_TEMP
GROUP BY ID
The problem is that while the first view returns the same results as the subquery, the second view gives me wrong date values.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
用途:
我还没有测试过这个来创建视图,但我记得MySQL不允许在视图中使用子查询。 根据文档,关于视图限制:
此外,如果有 2 个以上 id 值具有相同的最大日期值,则可能会出现重复项 - 如有必要,请将
DISTINCT
添加到查询中。自连接保证统计列返回的值 - 如果依赖 MySQL 的 GROUP BY 功能中的隐藏列,则不能这样说:
Use:
I haven't tested this for creating a view, but I recall that MySQL didn't allow subqueries in views. According to the documentation, about view restrictions:
Additionally, there is the chance for duplicates if there's 2+ id values with identical max date values -- Add
DISTINCT
to the query if necessary.The self join guarantees that the value returned for the stat column - that can't be said if relying on MySQL's hidden column in the GROUP BY functionality: