现在的位置: 首页 > 综合 > 正文

mysql limit 处理多个返回结果

2013年08月28日 ⁄ 综合 ⁄ 共 982字 ⁄ 字号 评论关闭

今天项目中又遇到一个 mysql 查询数据的问题,简单说就是当你想处理一个查询(可能返回多个记录)时,可以用

limit 来解决一些问题。

eg:

select a.*, (select b.id from table_b b where .......) as t1 from table_a a

如果:(select b.id from table_b b where .......) 返回多条结果时,将出错。(可否在t1中将返回的结果拼成一个字符串?在前台再去根据规则解析呢? 想过这个问题
。不过还可以用limit来达到这种要求。)


解决如下:

select tt.*
,(select s.name from tbl_rel_route_has_destination rhd,tbl_obj_scene s  where rhd.sceneid=s.id and rhd.routeid= (select sp.routeid from tbl_obj_sale_plan sp where sp.id=tt.planid) limit 1  ) as des1
,(select s.name from tbl_rel_route_has_destination rhd,tbl_obj_scene s  where rhd.sceneid=s.id and rhd.routeid= (select sp.routeid from tbl_obj_sale_plan sp where sp.id=tt.planid) limit 1,1) as des2
from tbl_obj_travel_team tt
where tt.cityid = (select gov.cityid from tbl_obj_government gov ,tbl_obj_user u where u.governmentid=gov.id and u.id = 1)

若 limit 1,1 即查询结果的第2条数据 不存在,将返回null,前台再做判断.(达到目的了)

limit 用法:

第一个参数:起始偏移量(0开始)。

第二个参数:要限制查询的 记录数。

注意问题:

1.若只有一个参数。eg: limit 10        返回前10条。limit n 相当于 limit 0,n

2.二个参数                eg: limit 10,10  返回11-20条。

3.为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 
-1. limit 10,-1

抱歉!评论已关闭.