create table `tb_article`( `id` int not null primary key auto_increment comment '主鍵', `author_id` int not null comment '作者id', `category_id` int not null comment '文章類別id', `views` int not null comment '閱讀量', `comments` int not null comment '評論量', `title` varchar(200) not null comment '文章標(biāo)題', `content` text not null comment '文章內(nèi)容' ) comment '文章表'; insert into tb_article(author_id,category_id, views, comments, title, content) values(1,1,1,1,1,1); insert into tb_article(author_id,category_id, views, comments, title, content) values(2,2,2,2,2,2); insert into tb_article(author_id,category_id, views, comments, title, content) values(1,1,3,3,3,3,);
需求:
查詢出 類別id為1 且 評論量大于1的情況下,閱讀量最多的那篇文章的作者id。
SQL寫法如下:
select id, author_id from tb_article where category_id = 1 and comments > 1 order by views desc limit 1;
create table `tb_novel`( `id` int not null primary key auto_increment comment '主鍵', `title` varchar(100) not null comment '小說名' ) comment '小說';
create table `tb_character`( `id` int not null primary key auto_increment comment '主鍵', `name` varchar(100) not null comment '人物名', `novel_id` int not null comment '歸屬于的小說id' ) comment '人物';
create table `tb_kongfu`( `id` int not null primary key auto_increment comment '主鍵', `kongfu_name` varchar(100) not null comment '功夫的名字', `novel_id` int not null comment '小說的id' )comment '功夫';
insert into tb_novel(title)values('天龍八部'); insert into tb_novel(title)values('射雕英雄傳'); insert into tb_novel(title)values('神雕俠侶'); insert into tb_novel(title)values('倚天屠龍記');
insert into tb_character(name, novel_id) values('喬峰',1); insert into tb_character(name, novel_id) values('掃地僧',1); insert into tb_character(name, novel_id) values('洪七公',2); insert into tb_character(name, novel_id) values('郭靖',2); insert into tb_character(name, novel_id) values('金輪法王',3); insert into tb_character(name, novel_id) values('小龍女',3); insert into tb_character(name, novel_id) values('趙敏',4); insert into tb_character(name, novel_id) values('滅絕老尼',4);
insert into tb_kongfu(kongfu_name, novel_id) values('北冥神功', 1); insert into tb_kongfu(kongfu_name, novel_id) values('六脈神劍', 1); insert into tb_kongfu(kongfu_name, novel_id) values('落英神劍掌', 2); insert into tb_kongfu(kongfu_name, novel_id) values('北斗七星陣', 2); insert into tb_kongfu(kongfu_name, novel_id) values('黯然銷魂掌', 3); insert into tb_kongfu(kongfu_name, novel_id) values('龍翔般若功', 3); insert into tb_kongfu(kongfu_name, novel_id) values('乾坤大挪移', 4); insert into tb_kongfu(kongfu_name, novel_id) values('九陰白骨爪', 4);
需求:
查詢出屬于同一部小說的人物名和功夫的名字。
SQL寫法如下:
select c.name,f.kongfu_name from tb_character c left join tb_kongfu f on c.novel_id = f.novel_id;