更改表合并列中具有相同值的2行

时间:2014-04-01 14:45:11

标签: php mysql alter

我有一个表,我想合并两行具有相同名称的数据,如下所示:

id | name    | price | priced

1  | Samsung | 100   | 0

2  | Samsung | 0     | 500

我希望最后的输入是:

id               | name    | price | priced

(doesn't matter) | Samsung | 100   | 500 

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT MAX(id) as id, name,MAX(price) as price, MAX(priced) as priced
FROM TableName
GROUP BY name

要插入表格:

INSERT INTO Table2 VALUES
(SELECT MAX(id) as id, name,MAX(price) as price, MAX(priced) as priced
FROM TableName
GROUP BY name)

修改

正如你所说,合并(插入新的和删除其他人)

INSERT INTO TableName VALUES
(SELECT MAX(id)+1 as id, name,MAX(price) as price, MAX(priced) as priced
FROM TableName
GROUP BY name)

--Now deleting others
DELETE T1 FROM TableName T1, TableName T2 WHERE T1.id < T2.id AND T1.name = T2.name

答案 1 :(得分:1)

你想要这个吗?

 select id , name,
 sum(price) as price, sum(priced) as priced from table1
 group by name

答案 2 :(得分:0)

我知道你想加价不是最大的。我想你应该换个新桌子&#39; table2&#39;并按以下方式向其添加行:

INSERT INTO table2 Values (
SELECT
  name,
  SUM(price),
  SUM(priced)
FROM table1
GROUP BY name )

然后删除table1。这样,您将从table1

添加具有相同名称的行