2017-06-03 109 views
0

我在MSQL三個表的值的列表如下所示MySQL查詢:用於在單個細胞

customer_details:

cust_id  cust_name Mob_No 
----------------------------------------- 
1   john  9999999999 
2   Rex   1234567890 

customer_services:

cust_id  service_id 
-------------------------- 
1   s1 
2   s2 
1   s2 

m_service:

service_id service_name 
---------------------------- 
s1    IT 
s2    VAT 

我需要結果如下:

cust_id  cust_name service_name 
-------------------------------------------- 
1  John  IT, VAT 
2  Rex   VAT 

我試過如下:

SELECT a.cust_id,a.cust_name, c.service_name 
FROM customer_details a, customer_service b, m_service c 
WHERE a.cust_id=b.cust_id AND b.service_id=c.service_id; 

但我需要在同一行中的服務名稱。任何幫助是非常可觀的

感謝和問候 Biswa

+0

不保存CSV在一列http://stackoverflow.com/questions/41304945/best-type-of-indexing-when-there-is-like-clause/41305027#41305027 http://stackoverflow.com/questions/41215624/sql -table-entry-vs-sql-table-with-a-row-for-each-entry/41215681#41215681 – e4c5

+0

考慮處理應用程序代碼中的數據顯示問題 – Strawberry

回答

0

您可以使用MySQL的GROUP_CONCAT()函數生成,你在你的輸出需要的服務名稱的CSV列表:這裏

SELECT 
    t1.cust_id, 
    t1.cust_name, 
    GROUP_CONCAT(t3.service_name) AS service_name 
FROM customer_details t1 
INNER JOIN customer_services t2 
    ON t1.cust_id = t2.cust_id 
INNER JOIN m_service t3 
    ON t2.service_id = t3.service_id 
GROUP BY 
    t1.cust_id, 
    t1.cust_name 

演示:

Rextester