网上看到的例子

create table person
(
userId int(11) auto_increment,
userName varchar(50),
primary key(userId)
)default charset=utf8;


create table article
(
articleId int(11) auto_increment,
userId int(11),
title varchar(50),
content text,
foreign key(userId) references person(userId),
primary key(articleId)
)default charset=utf8;


create table vote
(
voteId int(11) auto_increment,
articleId int(11),
score int(20),
foreign key(articleId) references article(articleId),
primary key(voteId)
)default charset=utf8;

insert into person(userName) values('aaa'),('bbb'),('ccc');
insert into article(userId,title) values(1,'aaaaaaaaaaa'),(1,'bbbbbbbbbbb'),(1,'cccccccccccccc'),(3,'fffffffff'),(3,'gggggggg'),(3,'wwwwwww');
insert into vote(articleId,score) values(1,20),(2,30),(3,250),(4,130),(5,80),(6,300);

###1.查询所有没有发表过文章的用户名;###传说select 1 from article a where a.userId = p.userId and a.userId is not null中select 1 ...能提高效率;exists 返回的只是true or false
select p.userName from person p where  not exists(select 1 from article a where a.userId = p.userId and a.userId is not null);

###2.查询得票数大于100的所有文章标题,按得票数降序排列
select a.title,v.score from article a left join vote v on a.articleId=v.articleId where v.score >100 order by v.score desc;

###3查询发表文章数大于2,文章平均得票数大于100的用户,按平均得票数倒序
#--文章数大于2
 #--select * from article a group by a.userId having(count(a.articleId))>2;

select
    p.userName from person p inner join (select a.userId id from article a inner join vote v on a.articleId = v.articleId where a.userid in (select a.userId from article a group by a.userId having(count(a.articleId))>2) group by a.articleId having(avg(v.score))>100 )
    result on p.userId=result.id;

你可能感兴趣的:(网上看到的例子)