首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

具有附加列的同一个表上的多对多

关系,在创建表的时候,您可以使用 created_atupdated_at 列来追踪记录的生命周期。在插入多对多关系记录时,您可以使用 through 中间表,并在 through 表中添加 created_atupdated_at 列来记录创建时间和更新时间。对于查询,您可以使用 with_created_atwith_updated_at 子查询来获取记录创建时间和更新时间。

例如,在以下模型中,我们定义了一个 through 中间表,用于记录 usersposts 之间的多对多关系:

代码语言:sql
复制
CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  email VARCHAR(255) UNIQUE NOT NULL
);

CREATE TABLE posts (
  id SERIAL PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  content TEXT NOT NULL,
  user_id INTEGER NOT NULL REFERENCES users(id)
);

CREATE TABLE post_views (
  id SERIAL PRIMARY KEY,
  post_id INTEGER NOT NULL REFERENCES posts(id),
  user_id INTEGER NOT NULL REFERENCES users(id),
  created_at TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

在插入多对多关系记录时,我们使用 through 中间表,并在 through 表中添加 created_atupdated_at 列来记录创建时间和更新时间:

代码语言:sql
复制
INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com');
INSERT INTO posts (title, content, user_id) VALUES ('Hello World', 'This is a test post.', 1);
INSERT INTO post_views (post_id, user_id, created_at, updated_at) VALUES (1, 1, NOW(), NOW());

对于查询,我们可以使用 with_created_atwith_updated_at 子查询来获取记录创建时间和更新时间:

代码语言:sql
复制
SELECT users.id AS user_id, users.name AS user_name, users.email AS user_email, 
       posts.id AS post_id, posts.title AS post_title, posts.content AS post_content, 
       post_views.created_at AS created_at, post_views.updated_at AS updated_at
FROM users
JOIN (
  SELECT post_id, user_id, created_at, updated_at
  FROM post_views
  WHERE post_id = 1 AND user_id = 1
) post_views ON users.id = post_views.user_id
JOIN posts ON posts.id = post_views.post_id;

这样,您就可以在同一个表上使用多对多关系,并轻松地跟踪记录的生命周期。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

19分32秒

16. 尚硅谷_佟刚_JPA_映射双向多对多的关联关系.avi

4分25秒

38-使用级联处理多对一的映射关系

6分24秒

39-使用association处理多对一的映射关系

17分57秒

40-使用分步查询处理多对一的映射关系

12分4秒

42-通过collection处理一对多的映射关系

12分8秒

43-通过分步查询处理一对多的映射关系

3分26秒

45_尚硅谷_大数据MyBatis_扩展_分步查询多列值的传递.avi

5分18秒

43_尚硅谷_MyBatis_通过association解决多对一的映射关系

11分18秒

46_尚硅谷_MyBatis_通过collection解决一对多的映射关系

11分47秒

42_尚硅谷_MyBatis_通过级联属性赋值解决多对一的映射关系

16分23秒

44_尚硅谷_MyBatis_通过分步查询解决多对一的映射关系

15分23秒

12. 尚硅谷_佟刚_JPA_映射单向多对一的关联关系.avi

领券