中间表三表联查

示例表:

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

你可能感兴趣的:(中间表三表联查)