Mysql合并行

时间:2013-04-02 09:37:13

标签: mysql group-by

我有这张桌子:

ip   country

1     A
2     A
3     B
4     B
4     B

我正在尝试编写一个查询,它将返回如下内容:

A 1,2
B 3,4

E.g。 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
}
}`

5 个答案:

答案 0 :(得分:11)

试试这个:

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

<强> SQL Fiddle

答案 1 :(得分:1)

如果您不希望重复值4,则可能需要在ip前面添加'DISTINCT'。

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

答案 2 :(得分:0)

试试此Query,您可以在 STUFF

中使用 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

答案 3 :(得分:0)

试试这个:

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

SQL FIDDLE HERE

答案 4 :(得分:0)

试试这个

              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 )