日期:2014-05-17  浏览次数:20917 次

3个表联合查询,怎么写SQL ?
超市抽奖活动查询

表a:(抽奖时间公布表)
字段:ID(序号) ,start_time(开始时间) ,end_time(结束时间) ,name(本次抽奖活动名称)
数据如:
001,2008-10-10 ,2008-10-15 ,饮料促销活动
002,2008-11-10 ,2008-11-15 ,蔬菜促销活动
003,2008-12-10 ,2008-12-15 ,粮油促销活动

表b: (客户在超市消费的积分表)
字段:user_id(客户ID) , user_name(客户名字) ,xf_time(消费时间),score(积分)
数据如:
000001,小李,2008-12-10,5
000001,小李,2008-12-11,3
000002,小一,2008-12-14,5
000002,小一,2008-12-13,3
000003,小二,2008-12-10,1
000003,小二,2008-12-14,3
000004,小三,2008-12-14,1

表c: (参加抽奖活动记录表)
字段:ID(序号) ,user_id(客户ID) ,use_name(客户名字) ,record(抽奖记录)
数据如:
002,000004, 小三,抽了第一注
002,000004, 小三,抽了第二注
002,000002, 小一,抽了第一注

表之间的关联:a.ID = b.ID


我想查询的结果是:
再距当前最近的抽奖活动日期范围里,有那些客户在超市消费了,而且消费积分超过3分的就可以抽5注,积分小于小分的只能抽3注,
并且能得到,当前用户是否已经参加抽奖了,如果已经参加了,那他还可以再抽几注?

SQL 怎么写呢?

------解决方案--------------------
可抽注数:
select b.user_id, b.user_name,case when b.score>3 then 5 else 3 end 可抽注数
from 
b,(select max(end_time) end_time from a)a
where b.xf_time=a.end_time 

------解决方案--------------------
select b.user_id, b.user_name,case when b.score>3 then 5 else 3 end 可抽注数,c.num 已抽注数
from b,(select max(end_time) end_time from a)a
on b.xf_time=a.end_time 
left join (select user_id,user_name,count(*) num from c group by user_id,user_name)c
on b.user_id=c.user_id and b.user_name=c.user_name
------解决方案--------------------

表之间的关联:a.ID = b.ID

b里面有id?

只要用子查询+关联就可以了
------解决方案--------------------
SQL code

select a.id ,(user_id,case  
                       when score>3 then 5
                       else 3 
                       end as times ,record
from a,(select  b.user_id,score,max(xf_time)as last_time ,record from b ,c
where b.user_id = c.user_id
group by b.user_id,score,record) f
where a.end_time<f.last_time
--楼主在加上详细的条件

------解决方案--------------------
SQL code

select a.id ,user_id,case  
                       when score>3 then 5
                       else 3 
                       end as times ,record
from a,(select  b.user_id,score,max(xf_time)as last_time ,record from b ,c
where b.user_id = c.user_id
group by b.user_id,score,record) f
where a.end_time<f.last_time
--楼主在加上详细的条件

------解决方案--------------------
select b.user_id,
case
when max(b.score) > 3 then
5
else
3
end 可抽注数,
count(c.user_id) 已抽注数
from b,c
 where b.user_id = c.user_id(+)
 group by b.user_id
不知道楼主想查出ID字段的意义是什么,若说是最近的但是抽奖活动记录表中没得时间字段,仅给出部分代码以供参考
感觉表的设计结构有所累赘
------解决方案--------------------
上面的语句还有点问题,更新如下:
select b.user_id,
case
when max(b.score) > 3 then
5
else
3
end 可抽注数,
case
when (select count(c.user_id)
from c
where user_id = b.user_id
group by user_id) is null then
0
else
(select count(c.user_id)
from c
where user_id = b.user_id
group by user_id)
end 已抽注数
from b, c
 where b.user_id = c.user_id(+)
 group by b.user_id
继续跟踪,发现有问题或更好的方法请指教

------解决方案--------------------