2016-11-21 69 views
0

我有一個兩表加入其中一個表包含產品數據和其他定價數據,包括多個折扣定價。並非每個產品在定價表中都有多個條目,因爲某些產品只有單個單價。 我想弄明白的是在我的選擇如何設置一個標誌,讓我知道如果一個產品有多個定價可用。mysql加入選擇最低價格集標誌

我現在有的代碼(見下文)會返回產品並找到每種產品的最低價格。然而就像我說的,並不是所有的產品都有「最低價格」。我試圖確定產品的價格是單個單價還是最低價。

SELECT products.* 
    , products_pricing.* 
    FROM products 
    LEFT 
    JOIN products_pricing 
    ON products.product_id = products_pricing.product_id 
    LEFT 
    JOIN products_pricing AS filter 
    ON products_pricing.product_id = filter.product_id 
    AND products_pricing.qty_price > filter.qty_price 
WHERE filter.product_id IS NULL 
    AND products.product_active > 0 
ORDER 
    BY products.product_id DESC 
+1

(我不熟悉MySQL),但你可以子查詢產品嗎?也許像這樣,你加入到子查詢中,或者將它保存爲你加入的'視圖'? SELECT \t MIN(PRICE), CASE WHEN COUNT(*)= 1 THEN 1 ELSE 0 END AS SINGLE_PRICE 產品來自 GROUP BY PRODUCT_ID – Sean

+0

將所期望的結果是什麼樣的?更好的是,請參閱http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple- sql-query – Strawberry

回答

0

從你的描述我收集每一件產品在products_pricing至少一個價格,因此無需外部連接。

而不是使用反連接模式,我會簡單地加入聚合產品。然後使用最小/最大或計數的比較來得到您的旗幟。

select 
    p.*, 
    pp.*, 
    case when ppm.min_qty_price = ppm.max_qty_price then 'single' else 'multi' end as flag 
from products p 
join products_pricing pp on pp.product_id = p.product_id 
join 
(
    select product_id, min(qty_price) as min_qty_price, max(qty_price) as max_qty_price 
    from products_pricing 
    group by product_id 
) ppm on ppm.product_id = pp.product_id 
     and ppm.min_qty_price = pp.qty_price 
where p.product_active > 0 
order by p.product_id desc; 
+0

新的在這裏,並不確定是否可以說謝謝,因此有可能在政治上是不正確的......謝謝!這只是我所需要的,並且完美地工作。 – NTFM

0

如果dpn't需要所有來自這兩個表列,但只相關列

SELECT products.product_id, count(*) as num_of_price 
    , case when count(*) > 1 then 'MULTI PRICE' ELSE 'SINGLE PRICE' as flag_price 
    FROM products 
    LEFT 
    JOIN products_pricing 
    ON products.product_id = products_pricing.product_id 
WHERE products.product_active > 0 
    GROUP BY products.product_id 
ORDER 
    BY products.product_id DESC 

而如果你需要的所有列,您可以加入這個結果

SELECT products.* 
    , products_pricing.* 
    , t.* 
    FROM products 
    LEFT JOIN products_pricing ON products.product_id = products_pricing.product_id 
    LEFT JOIN (
     SELECT products.product_id, count(*) as num_of_price 
     , case when count(*) > 1 then 'MULTI PRICE' ELSE 'SINGLE PRICE' as flag_price 
     FROM products 
     LEFT 
     JOIN products_pricing 
     ON products.product_id = products_pricing.product_id 
    WHERE products.product_active > 0 
     GROUP BY products.product_id 
    ) T ON products.product_id = T.product_id 
ORDER 
    BY products.product_id DESC