【问题标题】:Mysql one to many relationshipMysql 一对多关系
【发布时间】:2011-07-06 22:23:53
【问题描述】:

我有两张桌子:

带有 IDItem 字段的 TABLE 项目 带有 IDcomment、IDItem、datePublished 和评论字段的 TABLE cmets。

如果我想列出最后 10 个 cmets 没问题,我只需对“cmets”表进行排序。问题是当我想列出单个项目的最后十个 cmets 时,这意味着项目不会重复。

在使用索引方面有什么最好的方法来实现这一点?如果我按“cmets”排序并按 IDItem 分组,我不会得到每个项目的最后一条评论,因为该组似乎是随机排序的:-(

我找到了将“lastDate”带到“items”表的解决方案,这样我就可以按项目排序,我将获得正确的排序顺序,但是当我加入 cmets 表时,我会得到 10 行相同的项目id 如果它有 10 个 cmets :-(

如何正确连接一对多,这样我只能从左表中获得一项,而在右表中获得一项?

我不确定我是否很清楚。

【问题讨论】:

  • 你能发布一个你想要得到什么输出的样本吗?

标签: mysql join relationship


【解决方案1】:

听起来您正在尝试返回具有最近 10 个 cmets 的 10 个项目,每个项目有一条评论正确?

如果是这样,试试这个:

SELECT * FROM Items I
JOIN
(SELECT TOP 10 * FROM Comments C2 WHERE DatePublished=
       (SELECT MAX(DatePublished) FROM Comments C3 WHERE C2.IDItem=C3.IDItem)
       ORDER BY DatePublished DESC) C1
ON I.IDItem=C1.IDItem

已编辑:删除了额外的 SELECT 并添加了 10 个 cmets 返回的限制

【讨论】:

  • 顺便说一句,这假设 DatePublished 是一个精确到毫秒的时间戳。如果它是一个简单的日/月/年时间戳,请告诉我,因为您需要不同的查询
【解决方案2】:
DECLARE @item TABLE
(
  IDItem int
)
DECLARE @comment TABLE
(
  IDComment int,
  DatePublished date,
  IDItem int,
  Comment varchar(100)
)

INSERT INTO @item (IDItem) VALUES (1);
INSERT INTO @item (IDItem) VALUES (2);
INSERT INTO @item (IDItem) VALUES (3);
INSERT INTO @item (IDItem) VALUES (4);

INSERT INTO @comment (IDComment, DatePublished, IDItem, Comment) VALUES (1,'2011-01-01', 1, 'test1');
INSERT INTO @comment (IDComment, DatePublished, IDItem, Comment) VALUES (2,'2011-01-02', 1, 'test2');
INSERT INTO @comment (IDComment, DatePublished, IDItem, Comment) VALUES (3,'2011-01-01', 2, 'test3');
INSERT INTO @comment (IDComment, DatePublished, IDItem, Comment) VALUES (4,'2011-01-03', 2, 'test4');
INSERT INTO @comment (IDComment, DatePublished, IDItem, Comment) VALUES (5,'2011-01-02', 3, 'test5');
INSERT INTO @comment (IDComment, DatePublished, IDItem, Comment) VALUES (6,'2011-01-05', 3, 'test6');

SELECT i.IDItem, (SELECT TOP 1 c.Comment FROM @comment c WHERE c.IDItem = i.IDItem ORDER BY c.DatePublished) FROM @item i

返回

   1    test1
   2    test3
   3    test5
   4    NULL

如果是你要找的,只要 mysql 这段代码。将 TOP 1 替换为 LIMIT 1 等。

【讨论】:

    【解决方案3】:

    (更新)这个呢?

    SELECT IDcomment, IDitem from COMMENTS where IDitem in (SELECT DISTINCT(IDitem) FROM comments); 
    

    【讨论】:

    • 您不能只对某些列使用 DISTINCT。
    猜你喜欢
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 2014-12-11
    • 2011-04-05
    • 1970-01-01
    相关资源
    最近更新 更多