在sql查询中连接数据

时间:2016-10-13 20:01:41

标签: sql ms-access

我有table1

     Pre    Ba          pre-Ba       kgs    fl
    6L34    1523726 6L34-1523726    0.01    Bm1
    6L34    1523726 6L34-1523726    0.04    Bm1
    6L34    1523726 6L34-1523726    0.06    Bm1
    BM51    13K732  BM51-13K732      0      Bm1
    BM51    13K732  BM51-13K732      8      Bm1

表2

 Pre    Ba          pre-Ba       kgs    fl
6L34    1523726 6L34-1523726    0.01    Bm2
BM51    13K732  BM51-13K732     0.02    Bm2
BM51    13K732  BM51-13K732        8    Bm2

我正在尝试将这些查询表合并为union all,但是将“fl”col与条件连接起来,例如:在表1中 pre-Ba col数据 6L34 -1523726 0.01 kgs与table2数据 6L34-1523726 匹配0.01 kgs所以结果应该是

Pre      Ba         pre-Ba       kgs    fl
6L34    1523726 6L34-1523726    0.01    Bm1&bm2
6L34    1523726 6L34-1523726    0.04    Bm1
6L34    1523726 6L34-1523726    0.06    Bm1
BM51    13K732  BM51-13K732     0       Bm1
BM51    13K732  BM51-13K732     8       Bm1
6L34    1523726 6L34-1523726    0.01    Bm2&bm1
BM51    13K732  BM51-13K732     0.02    Bm2
BM51    13K732  BM51-13K732     8       Bm2&bm1

如何在查询中指定?

1 个答案:

答案 0 :(得分:1)

通常你会用FULL OUTER JOIN来做这件事。但是......在Access中并不存在。所以你需要做两个查询,利用LEFT OUTER JOIN和一些逻辑确保没有重叠:

SELECT
    t1.pre,
    t1.ba,
    t1.pre-ba,
    t1.kgs,
    t1.f1 & "&" & t2.f1
FROM
    table1 as t1
    LEFT OUTER JOIN table2 as t2 ON
        t1.pre = t2.pre AND
        t1.ba = t2.ba AND
        t1.pre-ba = t2.pre-ba AND
        t1.kgs = t2.kgs

UNION ALL

SELECT
    t2.pre,
    t2.ba,
    t2.pre-ba,
    t2.kgs,
    t2.f2 & "&" & t1.f2
FROM
    table2 as t2
    LEFT OUTER JOIN table1 as t1 ON
        t2.pre = t1.pre AND
        t2.ba = t1.ba AND
        t2.pre-ba = t1.pre-ba AND
        t2.kgs = t1.kgs 

第一个查询获取Table1中的所有内容,但不包含Table2中的内容以及Table1 AND Table2中的内容。第二个查询只包含Table2中的内容。