2014-03-29 114 views
0

我有一個包含在三個字段的三個不同的表的主鍵逗號分隔值,例如表:MySQL查詢的逗號分隔的字段值

Table A (Main table): 
id title companyid countryid regulatorid 
1 tit1  1,2   2,3   2,1 
2 tit2  3,1   1,2   1,3 
Table B (company)   table c (Country)  table d(regulator) 
id title     id title   id  title 
1 comp1      1  country1  1  regul1 
2 comp2      2  country2  2  regulator2 
3 comp3      3  country3  3  regulator 

我想要得到的結果,如:

select id,title,group_concat(table B.title) AS company,group_concat(table c.title) AS 
country,group_concat(table d.title) AS regulator from table A INNER JOIN table b on 
find_in_set(table B.id,table A.companyid) > 0 INNER JOIN table c on find_in_set(table 
c.id,table A.countryid) > 0 INNER JOIN table d on find_in_set(table d.id,table 
A.regulatorid) > 0 

我有什麼改變來獲得CU:像

id  title  company  country     regulator 
1   tit1  comp1,comp2 country2,counrtry3  regulator2,regul1 
2  tit2   comp3,comp1 country1,country2  regul1,regulator3 

我已經查詢rrent結果?

+0

這就是爲什麼你必須規範你的數據。現在你處於SQL地獄。 –

回答

1

這是一個如此可怕的數據格式,在回答之前,我應該讓你保證在你有控制權的情況下改變格式。這應該是另外三個單獨的關聯/聯結表。如果您打算使用關係數據庫,請正確使用它。

select a.id, a.title, group_concat(distinct b.title), group_concat(distinct c.title), 
     group_concat(distinct d.title) 
from a left outer join 
    b 
    on find_in_set(b.id, a.companyid) > 0 left outer join 
    c 
    on find_in_set(c.id, a.countryid) > 0 left outer join 
    d 
    on find_in_set(d.id, a.regulatorid) > 0 
group by a.id, a.title; 

但它會很多很多很多更好的改變表格的佈局。

+0

你幫我如何規範這種類型的數據,請 –

+1

@Subhashkumar。 。 。這應該是另一個問題。大致如下:「我的數據看起來像這樣,在關係數據庫中存儲這些數據的最好方法是什麼。」 –

+0

我已經使用了這段代碼,我得到了結果,但表c和d的值正在重複 –