2014-07-09 61 views
0

仅用于实验目的。SQL,使用查询本身提供的数据构建查询

我想构建一个查询,但不查询为任何表提取的数据,而是查询自查询中提供的数据。像:

select numbers.* from (1, 2, 3) as numbers; 

select numbers.* from (field1 = 1, field2 = 2, field3 = 3) as numbers; 

,所以我可以做的事情一样

select 
    numbers.* 
from (field1 = 1, field2 = 2, field3 = 3) as numbers 
where numbers.field1 > 1; 

如果解决方案是特定的数据库引擎可以很有趣了。

+1

你可以做'选择号码* FROM(SELECT 1 AS A,2为B,3为C UNION SELECT 4,5,6)AS号码 – scragar

+0

@scragar您可以请您的解决方案创建一个答案?有用! – fguillen

回答

2

如果你想要的值,以便在单独的行,而不是在同一行的三个字段,方法是每一个union all链接的值相同,只是一行。

select * 
from(
    select 1 as FieldName union all 
    select 2 union all 
    select 3 union all 
    select 4 union all -- we could continue this for a long time 
    select 5 -- the end 
) as x; 

select numbers.* 
from(
    select 1 ,2, 3 
    union select 3, 4, 5 
    union select 6, 7, 8 
    union select 9, 10, 11 -- we could continue this for a long time 
    union select 12, 13, 14 -- the end 
) as numbers; 

这工作与MySQL Postgres的(以及大多数其他人也)。

[编辑]使用union all而不仅仅是union,因为您不需要从常量列表中删除重复项。给第一个select中的字段一个有意义的名字。否则,您无法在以后指定特定字段:where x.FieldName = 3

如果您没有为字段提供有意义的名称(如第二个示例中所示),那么系统(至少在此处测试过的MySQL)将为第一个字段分配名称“1”,将“2”分配为第二个等等。所以,如果你想指定的领域之一,你必须写这样的表达式:

where numbers.1 = 3 
+0

接受,因为它是最明确的答案,而不是引擎特定的。 – fguillen

+1

不,全是必要的。由于这是一个常量列表,所以任何重复都不会存在,除非它们是有意的。如果没有重复,那么对系统进行无效排序和重复数据删除是浪费周期,如果它们是故意的,那么您当然不希望删除重复数据。 – TommCatt

1

使用values排构造:

select * 
from (values (1),(2),(3)) as numbers(nr); 

或使用CTE。

with numbers (nr) as (
    values (1),(2),(3) 
) 
select * 
from numbers 
where nr > 2; 

编辑:我只注意到你也taggeg你的问题与mysql:上面会不会使用MySQL,只有Postgres的(和一些其他DBMS)

1

您可以使用子查询没有表像这样:

SELECT 
    numbers.* 
FROM (
    SELECT 
     1 AS a, 
     2 AS b, 
     3 AS c 
    UNION 
    SELECT 
     4, 
     5, 
     6 
) AS numbers 
WHERE 
    numbers.a > 1 

如果你喜欢的查询总是有一个表引用有是始终有1行,没有列名为DUAL一个伪表,你可以用它像这样:

SELECT 
    numbers.* 
FROM (
    SELECT 
     1 AS a, 
     2 AS b, 
     3 AS c 
    FROM 
     DUAL 
    UNION 
    SELECT 
     4, 
     5, 
     6 
    FROM 
     DUAL 
) AS numbers 
WHERE 
    numbers.a > 1 
+0

@a_horse_with_no_name确定删除... –