【问题标题】:Joining queries that get values from the other连接从另一个获取值的查询
【发布时间】:2015-04-01 20:57:51
【问题描述】:

我正在尝试使用从第一个选择到第二个选择的值运行以下 MS Access 查询: (这个问题起源于Using results from a query within the same query,但我对它做了很大的改动,我觉得它需要一个新问题)

SELECT 
A.field1,
A.field2,
A.field3,
FROM TheTable AS A
Where A.Id = 3;
?Join / UNION?
SELECT
B.field4,
B.field5
FROM TheTable AS B
Where B.Id = field1

最后,我希望有 5 列作为基于这两个查询的输出,但是我怎样才能正确地执行连接/联合呢?请注意,TheTable 在两个查询中都是相同的,但我在每个部分中使用它的方式不同...

我不会在第一行 3 个元素的下一行 2 列(和一个空值)。只要我能在一个查询中完成。

所以输出看起来像:

A.field1, A.field2, A.field3, B.field4, B.field5
1, 2, 3, 4, 5

等等

【问题讨论】:

  • 请编辑您的问题并提供示例数据和所需结果。

标签: sql ms-access


【解决方案1】:

只有在每个查询生成相同数量的行或一个总是生成更少的行时,连接才会起作用。

除此之外,您可以从一个查询或两个查询的联合中获得此输出。

联合其实更简单,更容易维护:

SELECT  A.field1, A.field2, A.field3, null Field4, null Field5
FROM    TheTable AS A
Where   A.Id = 3
union all
SELECT  null, null, null, B.field4, B.field5
FROM    TheTable AS B
Where   B.Id = field1;

单个查询效率更高,但也稍微复杂一些:

SELECT  case id when 3 then field1 else null end as Field1,
        case id when 3 then field2 else null end as Field2,
        case id when 3 then field3 else null end as Field3, 
        case id when 3 then null else field4 end as Field4, 
        case id when 3 then null else field5 end as Field5
FROM    TheTable AS A
Where   Id = 3
    or  Id = Field1;

但是,您必须回答的主要问题可能不是效率而不是可维护性。您必须考虑的一件事是 Field1 是否可以等于 3。如果情况确实如此,那么同一行将在“A”查询和联合中的“B”查询中生成一个元组。但是,正如所写,它只会在单个查询中生成一个包含 Field1、Field2 和 Field3 值以及 Field4 和 Field5 字段为 NULL 的元组。

因此,如果这应该是可能的(字段 1 = ID),您必须选择哪个查询可以为您的需求生成最佳结果。如果该条件不可行,请选择其中一个。

【讨论】:

    【解决方案2】:

    我想你想要的是

    SELECT 
    A.field1,
    A.field2,
    A.field3,
    B.field4,
    B.field5
    FROM TheTable  A inner join  TheTable AS B on
    B.Id = field1
    Where A.Id = 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-24
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-03
      • 2014-09-28
      相关资源
      最近更新 更多