2013-04-02 59 views
2

我有這個表:Mysql的行合併

ip country 

1  A 
2  A 
3  B 
4  B 
4  B 

我想編寫一個查詢,這將返回類似:

A 1,2 
B 3,4 

例如SELECT * FROM table GROUP BY國家回報:

A 1 
B 3 

但這不是理想的結果。

Ι可以運行這個簡單的查詢:

SELECT * FROM table ORDER BY ip 

編程會寫類似:

$c_ip=0; 
`while($row=mysql_fetch_array($result,MYSQL_ASSOC)){ 
if($row['ip'])!=$c_ip) 
{ 
$c_ip=$row['ip']; 
//new line!! 
}else 
{ 
//don't close <tr> code goes here 
} 
}` 
+0

你想同一個國家的ip逗號連續分隔嗎? – rahularyansharma

+0

一個簡單的答案:是 –

+0

可能[重複](http://stackoverflow.com/questions/14065277/sql-select-multiple-rows-in-one-column) – Luv

回答

9

試試這個:

SELECT country, GROUP_CONCAT(DISTINCT ip SEPARATOR ',') AS ips 
FROM my_table 
GROUP BY country 

SQL Fiddle

+2

根據SQL小提琴它不給正確回答。 (重複4次) – Luv

0

試試這個Query,您可以在SQL SERVER

SELECT 
    t1.country, 
    STUFF((
    SELECT distinct ', ' + cast(t2.ip as varchar) 
    FROM Table1 t2 
    WHERE t2.country = t1.country 
    FOR XML PATH ('')) 
    ,1,2,'') AS Names 
FROM Table1 t1 
GROUP BY t1.country; 

SQL FIDDLE

0

使用STUFF試試這個:

SELECT country, GROUP_CONCAT(ip) 
FROM table1 
GROUP BY country 

SQL FIDDLE HERE

0

嘗試IP的這個

   SELECT DISTINCT country, SUBSTRING(ConcateColumn,2,LEN(ConcateColumn)) 
    FROM Table t1 
    CROSS APPLY ( 
       select substring((SELECT ',' + ip 
        FROM Table t2 
        WHERE t2.country = t2.country 
        ORDER BY DescOfFault 
        FOR XML PATH('')),2,20000) 
        ) D (ConcateColumn) 
1

您可能需要添加 'DISTINCT' 盈方,如果你不希望值4要重複做。

SELECT country, GROUP_CONCAT(DISTINCT ip SEPARATOR ',') AS ids 
FROM my_table 
GROUP BY country