2015-12-16 28 views
0

我有4個表需要使用連接。該查詢返回重複行。然而,爲了簡單起見,我只會用2個表格發佈我的問題,因爲即使有2個表格,問題仍然存在。表稱爲product_offer和promo。該結構如下Mysql:使用連接時輸出重複和不正確

 
product_offer table: 
id product_id offer_id store_id validity 
1  1   1   1  2016-12-12 00:00:00 

2  2   2   1  2016-12-12 00:00:00 

3  3   3   1  2016-12-12 00:00:00 

4  1   4   1  2016-12-12 00:00:00 
 
promo table: 
id product_id store_id  name      
1  1   1   Buy 1 Get 1 free  

2  2   1   10% off  

3  3   1   $10 off  

4  1   1   Get Chips Free  

我試圖獲取特定產品的商店組合,所有優惠。我期待着得到這個

 
product_id offer_id store_id  name 
1   1   1  Buy 1 Get 1 Free 
1   4   1  Get Chips Free 

但是當我運行此查詢我正在下面的輸出是不正確的,有重複的行

 
    SELECT po.product_id, po.offer_id,po.store_id,o.name 
    from product_offer po 
    left join promo o on po.product_id = o.product_id 
    where po.product_id = 1 and po.store_id = 1 

 
product_id offer_id store_id  name 
1   1   1  Buy 1 Get 1 Free 
1   4   1  Buy 1 Get 1 Free 
1   1   1  Get Chips Free 
1   4   1  Get Chips Free 

我也想提高查詢和使用的concat(使用〜如分離器),以僅返回每PRODUCT_ID一行如下:

 
product_id offer_id store_id name 
1   1~4  1  Buy 1 Get 1 free~Get Chips Free 

回答

0

我意識到我在加入錯誤的列。當我在product_offer上更改offer_id上的聯結並在促銷上更改它時,它效果很好。

 
SELECT  po.product_id, group_concat(po.offer_id SEPARATOR '~') offer_id, po.store_id ,group_concat(o.name SEPARATOR '~') offer 
FROM product_offer po 
     LEFT JOIN 
    promo o ON po.offer_id = o.id 
WHERE 
    po.product_id = 1 and po.store_id = 1 
0

使用Group byGROUP_CONCAT

SELECT po.product_id,GROUP_CONCAT(DISTINCT po.offer_id SEPARATOR '~') offer_id 
,po.store_id,GROUP_CONCAT(DISTINCT o.name SEPARATOR '~') name 
from product_offer po 
left join promo o on po.product_id = o.product_id 
where po.product_id = 1 and po.store_id = 1 
Group by product_id 
+0

這是行不通的,因爲它給了我只有一行,而不使用GROUP_CONCAT與GROUP_CONCAT它給了我兩個報價重複兩次在買1送1免費〜獲取籌碼免費〜買1送1免費〜獲取芯片免費 – FBP

+0

SELECT po.product_id,GROUP_CONCAT(DISTINCT po.offer_id SEPARATOR '〜')從product_offer PO offer_id ,po.store_id,GROUP_CONCAT(DISTINCT o.name SEPARATOR '〜')名稱 左加入促銷o在PO。 product_id = o.product_id 其中po.product_id = 1和po.store_id = 1 Group by product_id –

+0

嘗試此查詢@FBP –

0

您想使用GROUP BY,這是什麼,它需要你選擇的列把它們放在一起,以避免重複的結果,其中在該列中的數據相匹配

SELECT po.product_id, po.offer_id,po.store_id,o.name 
    from product_offer po 
    left join promo o on po.product_id = o.product_id 
    where po.product_id = 1 and po.store_id = 1 
    GROUP BY product_id 

爲了串聯其中,有GROUP_CONCAT的選項,你可以在http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat

+0

這不起作用,因爲它只給出第一行 – FBP

-1

更多我覺得你offer_id

需要組

+0

這不起作用,因爲它返回2行,但名稱購買1獲得1免費重複在兩行。 – FBP