现在的位置: 首页Other>正文
(转载)关于一道sql的面试题 (非常精典)
2007年11月14日 Other 暂无评论 ⁄ 被围观 阅读(1,145)+

假设只有一个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来排序,这样实现真的好简单。其实这都考验我们对Sql的编成思想。
把上面的代码拿出来和大家分享,如果大家还有其他的方法也发上来。

给我留言

留言无头像?


[face=9] [face=8] [face=7] [face=6] [face=5] [face=4] [face=3] [face=30] [face=2] [face=29] [face=28] [face=27] [face=26] [face=25] [face=24] [face=23] [face=22] [face=21] [face=20] [face=1] [face=19] [face=18] [face=17] [face=16] [face=15] [face=14] [face=13] [face=12] [face=11] [face=10] [em=9] [em=8] [em=7] [em=6] [em=5] [em=4] [em=3] [em=30] [em=2] [em=29] [em=28] [em=27] [em=26] [em=25] [em=24] [em=23] [em=22] [em=21] [em=20] [em=1] [em=19] [em=18] [em=17] [em=16] [em=15] [em=14] [em=13] [em=12] [em=11] [em=10] ;) :| :x :twisted: :roll: :oops: :o :mrgreen: :lol: :idea: :evil: :cry: :arrow: :P :D :?: :? :) :( :!: 8O 8)