中间表三表联查

2019-10-07  本文已影响0人  OLDBIG9

示例表:

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
上一篇下一篇

猜你喜欢

热点阅读