1

我有一个内部联接,但如果它在 [prices.Item] 字段上找不到任何匹配项,我希望它选择一个默认行,例如在 [Prices] 中使用“未分配”作为 [Item] 和 [ Price]等于5。我的join代码如下:

SELECT 
    Orders.Item, 
    Orders.Quantity, 
    Prices.Price,
    Orders.Quantity * Prices.Price AS Cost
FROM
    Orders
    INNER JOIN
    Prices
        ON Orders.Item = Prices.Item
4

1 回答 1

0

为了获得您想要的结果,我们需要结合两个查询的结果:一个用于具有实际存在于 [Prices] 表中的价格的项目,另一个用于没有“真实”价格的项目。这是使用 UNION 查询完成的。

对于[订单]...

Item     Quantity
-------  --------
Edam            1
Gouda           2
Brie            3
Cheddar         4
Havarti         5

...和[价格]...

Item        Price
----------  -----
Edam           10
Gouda          11
Brie           12
Havarti        13
unassigned      5

...查询...

    SELECT 
        Orders.Item, 
        Orders.Quantity, 
        Prices.Price
    FROM 
        Orders 
        INNER JOIN 
        Prices 
            ON Orders.Item = Prices.Item
UNION ALL
    SELECT
        Orders.Item,
        Orders.Quantity,
        DLookup("Price","Prices","Item='unassigned'") AS Price
    FROM
        Orders
        LEFT JOIN
        Prices
            ON Orders.Item = Prices.Item
    WHERE Prices.Item IS NULL

...返回

Item     Quantity  Price
-------  --------  -----
Edam            1  10   
Gouda           2  11   
Brie            3  12   
Havarti         5  13   
Cheddar         4  5    

我们可以将该查询保存在 Access 中(与其他查询一起使用),或者我们可以在它周围放置一个“包装器”来进行计算

SELECT
    Item,
    Quantity,
    Price,
    Quantity * Price AS Cost
FROM
    (
            SELECT 
                Orders.Item, 
                Orders.Quantity, 
                Prices.Price
            FROM 
                Orders 
                INNER JOIN 
                Prices 
                    ON Orders.Item = Prices.Item
        UNION ALL
            SELECT
                Orders.Item,
                Orders.Quantity,
                DLookup("Price","Prices","Item='unassigned'") AS Price
            FROM
                Orders
                LEFT JOIN
                Prices
                    ON Orders.Item = Prices.Item
            WHERE Prices.Item IS NULL
    )

...这给了我们

Item     Quantity  Price  Cost
-------  --------  -----  ----
Edam            1  10       10
Gouda           2  11       22
Brie            3  12       36
Havarti         5  13       65
Cheddar         4  5        20
于 2013-10-21T22:05:46.217 回答