中间表三表联查

示例表:

CREATE TABLE IF NOT EXISTS authors (
    `author_id` INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    `name` VARCHAR(64) UNIQUE NOT NULL DEFAULT ''
)  ENGINE INNODB COMMENT '作者表';

create table if not exists articles (
    `article_id` int unsigned primary key auto_increment,
    `title` varchar(64) unique not null default '',
    `created_at` timestamp not null default CURRENT_TIMESTAMP,
    `updated_at` timestamp not null default CURRENT_TIMESTAMP
)engine innodb comment '文章表';

create table if not exists author_article (
    `article_id` int unsigned not null,
    `author_id` int unsigned not null,
    primary key (`author_id`,`article_id`)
)engine innodb comment '作者文章关联表';

按照文章的最新发布时间查找对应作者列表

SELECT 
    au.author_id AS author_id, au.name AS name
FROM
    (authors AS au
    LEFT JOIN author_article AS aa ON au.author_id = aa.author_id)
        LEFT JOIN
    articles AS ar ON aa.article_id = ar.article_id
ORDER BY ar.created_at DESC
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 示例表: 按照文章的最新发布时间查找对应作者列表
    OLDBIG9阅读 1,358评论 0 0
  • 点击查看原文 Web SDK 开发手册 SDK 概述 网易云信 SDK 为 Web 应用提供一个完善的 IM 系统...
    layjoy阅读 14,032评论 0 15
  • 用传统的绘画工具,点上天空的颜色,于传统服饰上绘以传统图腾 -勾勒 -调色 -填充 -成品 每一次都不容易,衣服是...
    乌龙老江阅读 372评论 3 6
  • 人生好像就是由很多很多烦心事组成的 上一件事还没搞定 下一件事就接踵而来 在不断的解决过程中 慢慢长大慢慢变老
    一姚阅读 123评论 0 0
  • 安静地离开,像我们从未相遇一样。 无视路过的熟悉,沉默才是自由的飞翔。 蓦然的情起,是寂寞的蛊毒在作怪。 秋雨泪花...
    常建元阅读 206评论 0 1