在SQL语法方面,我是一个菜鸟.
我当然有一个包含大量行和列的表:P让我们说它看起来像这样:
AAA BBB CCC DDD ----------------------- Row1 | 1 A D X Row2 | 2 B C X Row3 | 3 C D Z
现在我想创建一个高级select语句,它给我这个组合(伪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
我如何将这两个select语句组合成一个漂亮的select语句?
如果我像下面那样复杂化SQL(因为我自己的SQL语句包含一个exists语句),它会工作吗?我只是想知道如何组合选择,然后尝试将它应用于我更高级的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'
这给了我一个结果.但我希望将它与此select语句的副本结合使用,并在末尾添加AND,并且'Status'字段将使用类似'DELETED'的字符串进行更改.
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)
casperOne.. 61
你有两个选择.第一个是有两个结果集,它们将根据WHERE
子句中的条件设置'Test1'或'Test2' ,然后将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
语句中复制过滤条件.
你有两个选择.第一个是有两个结果集,它们将根据WHERE
子句中的条件设置'Test1'或'Test2' ,然后将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
语句中复制过滤条件.
如果他们来自同一张桌子,我认为UNION
是你正在寻找的命令.
(如果你需要从不同表的列中选择值,你应该看一下JOIN
......)