在一个表里要根据条件筛选出不同的数据,并把数据union一起。
案例表如下
-------------------------------------------------------
Id Type UserId Title Price Date
----------------------------------------------------
1 0 1 AAA 5 2007-05-11
2 1 1 hBBB 5 2007-05-10
3 1 1 3AAA 6 2007-05-10
4 0 4 4AAA 6 2007-05-09
5 1 4 dAAA 3.5 2007-05-09
6 1 3 fAAA 7 2007-05-09
7 1 2 gAAA 9 2007-05-09
8 0 4 sAAA 10 2007-05-09
9 1 5 aAAA 8.5 2007-05-09
10 1 6 aAAA 7 2007-05-09
------------------------------------------------------
查询如下:
SELECT TOP 5 t1.* FROM T t1 WHERE t1.Type=0
UNION
SELECT TOP 5 t2.* FROM T t2 WHERE t2.Type=1
ORDER BY Id DESC
要求每个查询的UserId不能重复
[解决办法]
select TOP 5 * from t where id in (SELECT distinct ID FROM T t1 WHERE t1.Type=0 )
UNION
select TOP 5 * from t where id in (SELECT distinct ID FROM T t2 WHERE t2.Type=1 )
ORDER BY Id DESC
[解决办法]
SELECT TOP 5 t1.* FROM T t1 WHERE not exists(select 1 from T where UserId=t1.UserId and t1.id <id) and t1.Type=0
UNION
SELECT TOP 5 t2.* FROM T t2 WHERE not exists(select 1 from T where UserId=t1.UserId and t1.id <id) andt2.Type=1
ORDER BY Id DESC
[解决办法]
select TOP 5 * from t where exists (SELECT distinct 1 FROM T t1 WHERE t1.Type=0 )
UNION
select TOP 5 * from t where exists (SELECT distinct 1 FROM T t2 WHERE t2.Type=1 )
ORDER BY Id DESC