现在我们假设只有一个table,名为pages,有四个字段,id, url,title,body。里面储存了很多网页,网页的url地址,title和网页的内容,然后你用一个sql查询将url匹配的排在最前, title匹配的其次,body匹配最后,没有任何字段匹配的,不返回。
就是上面这道面试题,让我想了一个下午,在网上找资料,最后用下面方法实现
SELECT * FROM page where url like ‘%baidu%‘ or title like ‘%baidu%‘ or like ‘‘ ORDER BY CHARINDEX(‘baidu‘, url) DESC, CHARINDEX(‘baidu‘, title) DESC, CHARINDEX(‘baidu‘, body) DESC |
但我感觉这种方法并不是最简单的,后来把这个方法发给面试的人,他给我了一种更简单方法,只要用基本的Sql语句就可以实现。代码如下
select a.[id],a.mark from ( select [page].[id],100 as mark from [page] where [page].[url] like ‘%baidu%‘ union select [page].[id],50 as mark from [page] where [page].[title] like ‘%baidu%‘ union select [page].[id],10 as mark from [page] where [page].[body] like ‘%baidu%‘ ) as a order by mark desc |
用union 实现联合查询,在每个查询语句中定义一个临时变量mark 并给mark赋值,在最后的输出时采用mark来排序,这样实现,非常简单,我感觉这题更多考研我们的编程思想。