乐趣区

关于mysql:Mysql多张表关联时的分页查询

示例表信息


# 作者表
CREATE TABLE `test_author` (`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键 ID',
  `author_name` varchar(255) NOT NULL COMMENT '作者名',
  `creator` int(11) NOT NULL COMMENT '创建人',
  `last_updater` int(11) NOT NULL COMMENT '最初更新人',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创立工夫',
  `last_update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新工夫',
  `delete_flag` int(1) NOT NULL DEFAULT '0' COMMENT '删除标记(0- 默认,1- 删除)',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='作者';

#书籍表
CREATE TABLE `test_book` (`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键 ID',
  `title` varchar(255) NOT NULL COMMENT '题目',
  `creator` int(11) NOT NULL COMMENT '创建人',
  `last_updater` int(11) NOT NULL COMMENT '最初更新人',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创立工夫',
  `last_update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新工夫',
  `delete_flag` int(1) NOT NULL DEFAULT '0' COMMENT '删除标记(0- 默认,1- 删除)',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='书籍';

#关系表
CREATE TABLE `test_topic_paper_related` (`book_id` int(11) NOT NULL COMMENT '书籍 ID',
  `author_id` int(11) NOT NULL COMMENT '作者 ID',
  PRIMARY KEY (`book_id`,`author_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='作者 - 书籍关联关系';

办法一

SELECT
    t.id,
    t.title,
    t.creator,
    t.last_updater,
    t.create_time,
    t.last_update_time,
    t.delete_flag,
    t2.author_name (
    SELECT
        t.id,
        t.title,
        t.creator,
        t.last_updater,
        t.create_time,
        t.last_update_time,
        t.delete_flag 
    FROM
        test_book AS t 
    WHERE
        t.id IN (
        SELECT
            book_id 
        FROM
            test_author_book_related 
        WHERE
        author_id IN (筛选项 ID 汇合)) 
        AND 其余筛选条件 
    ORDER BY
        t.last_update_time DESC,
        t.id 
        LIMIT 分页信息 
    ) t
    LEFT JOIN test_author_book_related t1 ON t.id = t1.book_id
    LEFT JOIN test_author t2 ON t1.author_id = t2.id
退出移动版