日期:2014-05-18  浏览次数:20424 次

帮忙写个SQL语句,谢谢!
有下面两张表
t_main(m_id)
t_detail(d_id,m_id,status)
t_mian为基本信息,基本信息下可以有多个t_detail详细信息,每个t_detail有个状态status字段,状态可以取值1、2
我想得到结果是:查找t_main的数量,条件是它的所有t_detail的状态status为1
如:t_main有数据:(m1)(m2)(m3)
t_detail有数据:(d1,m1,1)(d2,m1,1)(d3,m2,1)(d4,m2,2)(d5,m3,2)
m1下的detail数据有d1,d2状态都是1。m2下的detail数据有d3,d4但状态有1,2。m3下的detail数据有d5状态是2。
我要查找的就是t_main中有多少m1这样的数据。

谢谢!

------解决方案--------------------
试试:
select count(1)
from t_main a
left join t_detail b on a.m_id=b.m_id
group by a.m_id
having sum(case b.status when 1 then 0 else b.status end)=0
------解决方案--------------------
----创建测试数据
declare @t_main table(mid varchar(20))
declare @t_detail table(d_id varchar(20),m_id varchar(20),status int)
insert @t_main
select 'm1 ' union all
select 'm2 ' union all
select 'm3 ' union all
select 'm4 '
insert @t_detail
select 'd1 ', 'm1 ',1 union all
select 'd2 ', 'm1 ',1 union all
select 'd3 ', 'm2 ',1 union all
select 'd4 ', 'm2 ',2 union all
select 'd5 ', 'm3 ',2

----查询
SELECT * FROM @t_main as a WHERE
EXISTS(
select 1 from @t_detail as t where m_id = a.mid
and status = 1
and not exists(select 1 from @t_detail where m_id = t.m_id and status <> t.status))


/*结果
mid
--------
m1
*/
------解决方案--------------------
select a.m_id,b.status,count(*) num
from t_main a left join t_detail b on a.m_id=b.m_id
group by a.m_id,b.status
返回:
m_id status num
-------------------- ------ -----------
m1 1 2
m2 1 1
m2 2 1
m3 2 1

(所影响的行数为 4 行)
从中,可以得出(第一条记录的m_id)m1对应的(status为)1的记录共有(num)2条。