(my)sql 从可选 table 中获取结果

(my)sql get results from optional table

我有简单的定价模型:


**table reseller**

| **id** | **reseller** |

| 1     |    john |

| 2     |    mary |

| 3     |    peter |

**table products**

| **id** | **product** | **advisory_price** |

| 1     |     apple    |    1.99 |

| 2    |      pear    |     2.99 |

| 3     |     plumb    |    3.99 |

**table custom_price**

| **id** | **product_id** | **reseller_id** | **retail_price**

| 1     |     1        |        1         |        2.50 |

| 2     |     1        |        3         |        2.80 |

| 3     |     3        |        1         |        4.50 |

这个想法是自定义价格对于经销商来说是可选的,所以如果他们没有指定它并且因此 custom_price table 中不存在相应的行,则显示默认值 'advisory_price'

我最初的想法是:

SELECT 
    products.advisory_price, 
    custom_price.retail_price, 
COALESCE(retail_price, advisory_price) AS sales_price 
FROM products
LEFT JOIN custom_price
ON 
    products.id = custom_price.product_id
WHERE 
    (
    custom_price.reseller_id IS NULL 
        OR 
    custom_price.reseller_id='2'
    )

但这当然会导致行不显示,如果没有为这个经销商指定,但它是为其他经销商指定的。

然后我想到了一个联合:

SELECT 
    products.advisory_price, 
    custom_price.retail_price AS sales_price, 
FROM products
INNER JOIN custom_price
ON 
    products.id = custom_price.product_id
WHERE 
    custom_price.reseller_id='2'
UNION
SELECT 
    products.advisory_price AS retail_price, 
FROM products
WHERE products.id NOT IN 
    ( 
        SELECT product_id 
        FROM custom_price 
        WHERE reseller_id = '2' 
    )

基本上,如果指定,这会从 custom_price table 获取 retail_price AS sales_price,并连接自定义价格 [=42] 中没有对应行的所有默认价格=].

然后我想在 id 上订购,但它给出了一个错误,这可能很容易修复,但不知何故我觉得这个 UNION 有点矫枉过正,它可以用比这个非常大的查询更简单的方式来完成.

我说得对吗?如果是的话,怎么说?

您必须将 WHERE 的内容放入第一个查询的 ON 子句中:

SELECT 
products.advisory_price, 
custom_price.retail_price, 
COALESCE(retail_price, advisory_price) AS sales_price 
FROM products
LEFT JOIN custom_price
ON 
products.id = custom_price.product_id AND custom_price.reseller_id='2'

那么应该可以了