首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

sql话语UNION 中使用 ORDER BY 和 LIMIT

2012-07-03 
sql语句UNION 中使用 ORDER BY 和 LIMIT???? 今天在使用mysql查询一张表各个分类中的前几条数据时想到用un

sql语句UNION 中使用 ORDER BY 和 LIMIT

???? 今天在使用mysql查询一张表各个分类中的前几条数据时想到用union又必须进行排序,因此涉及到sql中的排序和分页,写好sql语句后运行总是报错或者查不到想要的数据。

?

经反复实验得知union中使用order by和limit的用法如下:

?

(1)已知表名Article(文章表)其中有字段type(所属分类)和date(发布日期),现在要获取type为1、2、3的记录的前10条最新发布的记录sql语句如下(select * from Article where type=1 order by date desc limit 10) union (select * from Article where type=1 order by date desc limit 10) union (select * from Article where type=2 order by date desc limit 10) union (select * from Article where type=3 order by date desc limit 10)

?需要注意的有以下几点:

?

    每条关联的select必须用()括起来每条语句都要有order和limit

(2)如果想对整体的联合结果进行排序分页的话则直接把order或者limit写到总执行语句的最后即可

?

热点排行