美文网首页
中间表三表联查

中间表三表联查

作者: OLDBIG9 | 来源:发表于2019-10-07 22:01 被阅读0次

    示例表:

    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
    

    相关文章

      网友评论

          本文标题:中间表三表联查

          本文链接:https://www.haomeiwen.com/subject/bxivuctx.html