2011-05-09 70 views
1

我花了幾天的時間試圖解決這個有限的成功,我敢肯定有一個簡單的答案,但迄今爲止沒有運氣,儘管相當多的研究,我害怕問題是我有限的SQL知識。MySQl合併行條件爲真的行

我有3張桌子。訂單,orders_products和orders_products_attributes。

我試圖返回一個結果表給定的順序,顯示相匹配的所有orders_products,並在orders_products_attributes行該產品在那裏存在合併(有時沒有屬性)

我有到這裏:

SELECT  oi.orders_id AS orderid 
,   oi.products_id AS ItemNumber 
,   oi.products_quantity AS Quantity 
,   oi.final_price AS CostPerUnit 
,  oi.products_name AS ItemTitle 
,  concat (patt.products_options_id, '-', patt.products_options_values_id) AS OptionCodes 
,  concat (patt.products_options, ': ', patt.products_options_values) AS OptionNames 
FROM  orders_products oi 
JOIN  orders o 
ON  o.orders_id = oi.orders_id 
LEFT JOIN orders_products_attributes patt 
ON   patt.orders_products_id = oi.orders_products_id AND patt.orders_id = oi.orders_id 
WHERE  o.orders_status =2 AND oi.orders_id =10346 
ORDER BY ItemNumber 

這是返回結果如下:

orderid ItemNumber Quantity CostPerUnit ItemTitle OptionCodes OptionNames 

10346 140  1  319.9982 Item 1 3-5  Choice: A 

10346 140  1  319.9982 Item 1 1-1  Choice2: B 

10346 210  1  112.5000 Item 5 NULL  NULL 

我試圖合併行且ItemNumber是一樣的,CON cat'ing OptionCodes和OptionNames他們存在直到結束:

orderid ItemNumber Quantity CostPerUnit ItemTitle OptionCodes OptionNames 

10346 140  1  319.9982 Item 1 3-5, 1-1 Choice: A, Choice2: B 

10346 210  1  112.5000 Item 5 NULL   NULL 

我一直在試圖GROUP_CONCAT這些,但只有在合併所有3行成功。

對不起,如果我很慢,但我似乎無法從這裏繼續前進。

TIA, 安德魯

+0

order_products表的主鍵是什麼:products_id? – Thomas 2011-05-09 16:40:25

+0

orders_products_id是該表的主鍵 – Andrew 2011-05-09 18:57:59

回答

0

你可以通過order_products表的唯一密鑰組。由於我不確定這是什麼,所以我只用Select子句中的所有列進行分組,除了我使用Group_Concat的列以外。

Select oi.orders_id As orderid 
    , oi.products_id As itemnumber 
    , oi.products_quantity As quantity 
    , oi.final_price As costperunit 
    , oi.products_name As itemtitle 
    , Group_Concat(Concat(patt.products_options_id, '-', patt.products_options_values_id)) As optioncodes 
    , Group_Concat(Concat(patt.products_options, ': ', patt.products_options_values)) As optionnames 
From orders_products oi 
    Join orders o 
     On o.orders_id = oi.orders_id 
    Left Join orders_products_attributes patt 
     On patt.orders_products_id = oi.orders_products_id 
      And patt.orders_id = oi.orders_id 
Where o.orders_status =2 
    And oi.orders_id =10346 
Group By oi.orders_id, oi.products_id 
    , oi.product_quantity, oi.final_price, oi.products_name 
Order By itemnumber 
+0

非常感謝@Thomas - 這既解決了我的問題,又幫助我學習。非常感激。 – Andrew 2011-05-09 19:04:21

0

你應該能夠使用GROUP_CONCAT像你說的,但爲了做到這一點,你也必須GROUP BY ItemNumber