2013-07-05 68 views
1

我寫了這個查詢來找到銷售什麼類別的商店列表。mysql group_concat逗號分隔的ID匹配名稱

SELECT GROUP_CONCAT(distinct(sub_category_id)) AS s, 
      vendor_id AS v 
     FROM link_products_lists_vendors 
     GROUP BY vendor_id; 

這導致,

+---------------------------------------+------------+ 
| category_ids       | vendor_ids | 
+---------------------------------------+------------+ 
| 24,28,25,16,26,23,27,2    |   3 | 
| 2          |   67 | 
| 19,28,17,16,20,2      |   68 | 
| 19,28,24,26,23,21,16,27,22,17,25,2 |  122 | 
| 16,2         |  123 | 
| 28,17,22,21,18,16,26,27,20,23,25,2 |  124 | 
| 22,19,21,20,16,24,28,25,23,26,2  |  125 | 
| 23,24,26,25,28,16,20,27,19,2   |  126 | 
| 19,26,28,18,20,27,22,16    |  127 | 
| 22,26,28,21,23,20,24,19,16,17,27,25,2 |  128 | 
| 2          |  129 | 
| 2          |  133 | 
| 19,20,28,16,27,25,21,23,26,24,22  |  135 | 
| 23,28,17,22,26,21,16,20,27,24,25,2 |  136 | 
| 19,17,16,21,23,26,22,25,27,20,28  |  137 | 
| 19,20,26,22,21,24,23,17,28,16,27,25,2 |  138 | 
| 19,20,23,28,26,21,24,16,27,22,25,17,2 |  139 | 
| 22,27,20,21,24,17,23,28,26,19,25,2 |  142 | 
| 19,28,17,20,2       |  143 | 
+---------------------------------------+------------+ 
19 rows in set (0.01 sec) 

我現在要的是什麼樣,

+-------------------------- -----------+--- ----------+ 
| category_names      | vendor_names | 
+---------------------------------------+--------------+ 
| mobiles,laptops,desktops    | abcShop | 
| mobiles        | xyzShop | 
| desktops,mouses,keyboards    | pqrShop | 
+---------------------------------------+--------------+ 

我的類別表作爲,

+----+---------------+ 
| id | name   | 
+----+---------------+ 
| 17 | desktops  | 
| 18 | external_hdds | 
| 26 | headphones | 
| 27 | headsets  | 
| 22 | keyboards  | 
| 16 | laptops  | 
| 24 | memory_cards | 
| 2 | mobile-phones | 
| 21 | mouses  | 
| 25 | pendrives  | 
| 19 | printers  | 
| 20 | routers  | 
| 23 | speakers  | 
| 28 | tablets  | 
+----+---------------+ 

供應商表作爲,

+-----+----------------------+ 
| id | name     | 
+-----+----------------------+ 
| 108 | abcShop    | 
| 109 | xyzShop    | 
| 45 | pqrShop    | 
| 89 | .     | 
| 63 | .     | 
| 64 | .     | 
+-----+----------------------+ 

我應該如何編寫一個不會顯示標識的查詢,而是使用顯示標識和顯示名稱的表格?我不知道從哪裏開始。請幫忙!

回答

3

剛剛加入其他表中,選擇那些價值,而不是

SELECT GROUP_CONCAT(distinct(c.name)) AS s, 
     v.name AS v 
    FROM link_products_lists_vendors l 
    JOIN categories c on l.category_id = c.id 
    JOIN vendors v on l.vendor_id = v.id 
GROUP BY v.name; 

這個工作,只要供應商名稱和描述名稱是唯一的。

+0

v.name和v.id之間的區別是什麼..我認爲沒有名稱是唯一的..我使用v.id ...任何方式它的工作..謝謝.. – beck03076

+0

這是一個很好的做法只包含SELECT部分​​中的東西,它是聚合或GROUP BY的一部分。 –