对于SQL语法,我是菜鸟。
我的桌子上当然有很多行和列:P可以这样说:
AAA BBB CCC DDD ----------------------- Row1 | 1 A D X Row2 | 2 B C X Row3 | 3 C D Z
现在,我想创建一个高级选择语句,将其组合起来(此处为伪SQLish):
select 'Test1', * from TABLE Where CCC='D' AND DDD='X' select 'Test2', * from TABLE Where CCC<>'D' AND DDD='X'
输出为:
Test1, 1, A, D, X Test2, 2, B, C, X
我如何将这两个选择语句组合成一个不错的选择语句?
如果我像下面那样复杂化SQL,它会起作用吗(因为我自己的SQL语句包含一个exist语句)?我只想知道如何组合选择,然后尝试将其应用于我的更高级的SQL。
select 'Test1', * from TABLE Where CCC='D' AND DDD='X' AND exists(select ...) select 'Test2', * from TABLE Where CCC<>'D' AND DDD='X' AND exists(select ...)
我的REAL SQL语句是这样的:
select Status, * from WorkItems t1 where exists (select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) ) AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01) AND TimeStamp>'2009-02-12 18:00:00'
这给了我一个结果。但是我想将其与该选择语句的副本结合在一起,并在其末尾添加AND,并且“状态”字段将使用“已删除”之类的字符串进行更改。
select 'DELETED', * from WorkItems t1 where exists (select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) ) AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01) AND TimeStamp>'2009-02-12 18:00:00' AND NOT (BoolField05=1)
您有两个选择。首先是具有两个结果集,这两个结果集将根据WHERE子句中的条件设置“ Test1”或“ Test2” ,然后将UNION它们组合在一起:
WHERE
UNION
select 'Test1', * from TABLE Where CCC='D' AND DDD='X' AND exists(select ...) UNION select 'Test2', * from TABLE Where CCC<>'D' AND DDD='X' AND exists(select ...)
这可能是一个问题,因为您将在TABLE上进行两次有效的扫描/查找。
另一种解决方案是从表中选择一次,然后根据TABLE中的条件设置“ Test1”或“ Test2”:
select case when CCC='D' AND DDD='X' AND exists(select ...) then 'Test1' when CCC<>'D' AND DDD='X' AND exists(select ...) then 'Test2' end, * from TABLE Where (CCC='D' AND DDD='X' AND exists(select ...)) or (CCC<>'D' AND DDD='X' AND exists(select ...))
这里要注意的是,您将不得不在CASE语句和WHERE语句中重复过滤条件。
CASE