SQL 按问题分组
我必须向数据库编写一个查询,该数据库具有这样的表:
TABLE HISTORY:
ID | ITEM_ID | USER_ID | DATE
历史记录
ITEM TABLE:
ID | NAME | OWNER_ID
表包含用户对项目的所有操作的记录。 我必须编写一个查询,从 HISTORY 表中获取所有不在所有者手中的项目。因此,它应该为每个项目获取最后一条记录,并从中仅选择那些掌握在其所有者之外的人手中的记录。
我尝试使用嵌套查询来编写它,但是如果我使用这样的子查询:
SELECT ITEM_ID, MAX(DATE)
FROM HISTORY
GROUP BY ITEM_ID
我无法获取该记录的 ID。因此,我无法循环嵌套查询结果,因为我不知道它们的 ID。
你能帮我吗?
PS 您能否建议我将来如何从带有 group by 子句的查询中获取不在 group by 语句中的列?
I have to write a query to database, that has such table:
TABLE HISTORY:
ID | ITEM_ID | USER_ID | DATE
and
ITEM TABLE:
ID | NAME | OWNER_ID
History table contains a records of all operations with items by users.
I have to write a query, that takes from HISTORY table all items, which are not in the hands of owner. So, it should take for each item last record and select from them only those, which holds in other than it's owner's hands.
I tried to write it using nested queries, but if I'm using such subquery:
SELECT ITEM_ID, MAX(DATE)
FROM HISTORY
GROUP BY ITEM_ID
I can't take ID of this record. So, I can't loop over the nested queries result's, because I don't know an ID of their ID's.
Could you help me?
P.S. And could you advise me to the future, how to take from queries with group by clause the columns, which not in group by statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我对这个问题的理解是,您想要所有最近历史记录条目是由非所有者用户创建的项目。如果我错了,请纠正我。
上面的查询假设日期时间在日期列中具有一定的唯一性保证。如果没有,你也许可以使用history.id,如果它是一个完美的自动递增身份列,并且你保证永远不会让任何人乱搞(好吧,也许不是那么严格,但你明白我的意思)。
在这种情况下:
My understanding of the question is that you want all items whose most recent history entry was made by a non-owner user. Please correct me if I'm wrong.
The above query assumes a datetime with some guarantee of uniqueness in the date column. If not, you might be able to use history.id if it is a perfectly auto-incrementing identity column and you promise never to let anyone mess with (ok, maybe not that strict, but you get my point).
In this case: