作为程序员一定要保持良好的睡眠,才能好编程

PHP/MySQL编程-几道面试题sql语句汇总

发布时间:2018-11-04

几道面试题汇总,并记录下来


1) 某内容管理系统中,表message有如下字段 
id 文章id 
title 文章标题 
content 文章内容 
category_id 文章分类id 
hits 点击量 

创建上表,写出MySQL语句 

2)同样上述内容管理系统:表comment记录用户回复内容,字段如下 
comment_id 回复id 
id 文章id,关联message表中的id 
comment_content 回复内容 


写出sql

现通过查询数据库需要得到以下格式的文章标题列表,并按照回复数量排序,回复最高的排在最前面 


文章id 文章标题 点击量 回复数量 


select r.id,r.name,u.total,u.role_id from web_role as r left join (select count(id) as total,role_id from web_user_role group by user_id) as u on u.role_id=r.id order by u.total desc;

这条语句是正解,虽然表不同,但是结构类似,





用一个SQL语句完成上述查询,如果文章没有回复则回复数量显示为0

这里我我使用了 ifnull() 这个函数  ifnull(c.total,0)  如果 c.total 不是null 就显示c.total  如果是null 则显示0

表1.png



未使用ifnull  则没有找到的数据  就显示null了

select n.id,n.classname,c.total from web_articlenav as n left join(select count(id) as total,nav from web_article group by nav) as c on c.nav=n.id;

使用了ifnull 就会把是null的显示成 0

select n.id,n.classname,ifnull(c.total,0) from web_articlenav as n left join(select count(id) as total,nav from web_article group by nav) as c on c.nav=n.id;


这表语句使用了order by 排序 desc

select n.id,n.classname,ifnull(c.total,0) as total from web_articlenav as n left join(select count(id) as total,nav from web_article group by nav) as c on c.nav=n.id order by c.total desc;



这表语句使用了order by 排序 desc 并进行了 limit 10

select 
n.id,n.classname,ifnull(c.total,0) as total from web_articlenav as n 
left join(select count(id) as total,nav from web_article group by nav) 
as c on c.nav=n.id order by c.total desc limit 10;



其他sql语句链表查询:


select r.id,r.name from web_role as r left join (select count(id) as total,role_id from web_user_role group by user_id) as u on u.role_id=r.id order by u.total desc;