Mysql 一对多关系
我有两个表:
带有 IDItem 字段的表项 带有 IDcomment、IDItem、datePublished 和 comment 字段的 TABLE 注释。
如果我想列出最后 10 条评论,没问题,我只需对“评论”表进行排序即可。问题是当我想列出单个项目的最后十条评论时,这意味着项目不重复。
在使用索引方面有什么最好的方法来实现这一点吗?如果我按“评论”排序并按 IDItem 分组,我不会得到每个项目的最后评论,因为该组似乎是随机排序的:-(
我找到了将“lastDate”引入“items”表的解决方案,所以我可以按项目排序,我将获得正确的排序顺序,但是当我加入评论表时,如果有 10 条评论,我会得到 10 行相同项目 id :-(
一对多连接的正确方法是怎样的我明白了左表中只有一项,右表中只有一项?
我不确定我是否很清楚。
I have two tables:
TABLE items with IDItem field
TABLE comments with IDcomment, IDItem, datePublished and comment fields.
If I want to list last 10 comments it is no problem, I just sort the 'comments' table. The problem is when I want to list last ten comments on the individual items, that means items are not duplicated.
Any best way to achieve this in regards to using indexes? If I order by 'comments' and group by IDItem I don't get the last comment out on each item as the group seems to order randomly :-(
I found solution to bring 'lastDate' to the 'items' table, so I can sort by the items and I will have the correct sort order, but when I join to the comments table I get 10 rows of the same item id if it had 10 comments :-(
How is the proper way to join one to many so I get only one item from the left table with one item on the right table?
I am not sure if I was very clear.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来您似乎正在尝试返回具有最近 10 条评论的 10 件商品,其中每件商品一条评论是否正确?
如果是这样,请尝试以下操作:
编辑:删除了额外的 SELECT 并添加了返回 10 条评论的限制
It sounds like you're trying to get the 10 items returned that have the most recent 10 comments, with one comment per item correct?
If so, try this:
Edited: Removed extra SELECT and added limit of 10 comments returned
返回
如果这就是您要寻找的内容,只需 mysql 这段代码即可。将 TOP 1 替换为 LIMIT 1 等。
RETURNS
If it's what are you looking for, just mysql this code. Replace TOP 1 with LIMIT 1 etc.
(已更新)那这个呢?
(Updated) What about this?