【问题标题】:(my)sql get results from optional table(mysql 从可选表中获取结果
【发布时间】:2017-06-09 09:49:56
【问题描述】:

我有简单的定价模型:


**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 表中不存在相应的行,则会显示默认的“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 表中获取 Retail_price AS sales_price,并连接在自定义价格表中没有对应行的所有默认价格。

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

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

【问题讨论】:

    标签: mysql sql optional relation


    【解决方案1】:

    您必须在第一个查询中将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'
    

    那么它应该可以工作

    【讨论】:

      猜你喜欢
      • 2020-09-30
      • 2013-12-26
      • 1970-01-01
      • 2015-01-21
      • 2017-04-25
      • 2015-09-09
      • 2019-09-08
      • 1970-01-01
      相关资源
      最近更新 更多