MySQL社区

 找回密码
 注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

搜索
查看: 6958|回复: 13
打印 上一主题 下一主题

[SQL类] 两个表left join 找出符合条件的记录

[复制链接]
1#
发表于 2011-8-3 12:58:55 | 显示全部楼层
本帖最后由 je_ck 于 2011-8-3 13:00 编辑

问题有些不清晰。
问题1:order_followup对单次order的跟踪只有2条,一条open,一条close。是吗?
问题2:每个order可以无限开启。是吗?
问题3:时间自然连续。即id的增加与时间是一致的。是吗?

给你2个思路
1:若允许有多个相同的order在order_followup中,利用open与close的个数匹配
2:若不允许有多个相同的order在order_followup中,利用序号相等的方式
2#
发表于 2011-8-3 12:59:19 | 显示全部楼层
回答完,我的问题后,我可以给你SQL语句
3#
发表于 2011-8-4 04:46:46 | 显示全部楼层
本帖最后由 je_ck 于 2011-8-4 06:07 编辑

每次每个order的open与close都是一一对应的吗?
对于某个order来说。状态如下:
open
open
close
它的是否是要的记录。(因为它连续2次open,一个close)
4#
发表于 2011-8-5 05:09:58 | 显示全部楼层
OK.好像没有88805,结果是88802、88804

select t1.order_no case when t1.c1>t2.c1 then 0 else 1 end as selectorder
(select  order_no,max( id)  as c1 from order_followup where  status = 'open' group by  order_no) as t1 left join
(select  order_no,max( id)  as c1 from order_followup where  status = 'close' group by  order_no) as t2
on ti.order_no = t2.order_no

selectorder为1的就是选中的。
5#
发表于 2011-8-6 06:00:43 | 显示全部楼层
是不是还有88806和88805没有查询出来。
6#
发表于 2011-8-6 06:02:50 | 显示全部楼层
完整SQL语句如下:
select order.* from order left join (select t1.order_no case when t1.c1>t2.c1 then 0 else 1 end as selectorder
(select  order_no,max( id)  as c1 from order_followup where  status = 'open' group by  order_no) as t1 left join
(select  order_no,max( id)  as c1 from order_followup where  status = 'close' group by  order_no) as t2
on ti.order_no = t2.order_no) as t3 on order.order_no = t3.order_no and selectorder = 1
您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|申请友链|小黑屋|Archiver|手机版|MySQL社区 ( 京ICP备07012489号   
联系人:周生; 联系电话:13911732319

GMT+8, 2024-5-17 12:42 , Processed in 0.064939 second(s), 24 queries , Gzip On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表