我有兩個具有相同列的表,第一列是名稱,第二列是計數。我想合併這些表,讓每個名字出現在兩個表的增加數:合併具有相同列名的兩個表,添加計數器
Table1: Table2: Result Table:
NAME COUNT NAME COUNT NAME COUNT
name1 1 name3 3 name1 1
name2 2 name4 4 name2 2
name3 3 name5 5 name3 6
name4 4 name6 6 name4 8
name5 5
name6 6
正如我已經創建了一個很醜的結構來執行這個時刻,並想知道如果有可能以更優雅的方式獲得結果。
我有什麼至今(表1是測試1和表2中的Test2):
create table test1 (name varchar(40), count integer);
create table test2 (name varchar(40), count integer);
create table test3 (name varchar(40), count integer);
create table test4 (name varchar(40), count integer);
create table test5 (name varchar(40), count integer);
insert into test4 (name, count) select * from test1;
insert into test4 (name, count) select * from test2;
insert into test3 (name , count) select t1.name, t1.count + t2.count
from test1 t1 inner join test2 t2 on t1.name = t2.name;
select merge_db(name, count) from test3;
insert into test5 (name, count) (select name, max(count) from test4 group by name);
CREATE FUNCTION merge_db(key varchar(40), data integer) RETURNS VOID AS
$$ -- souce: http://stackoverflow.com/questions/1109061/insert-on-duplicate-update-postgresql
BEGIN
LOOP
-- first try to update the key
UPDATE test4 SET count = data WHERE name = key;
IF found THEN
RETURN;
END IF;-- not there, so try to insert the key -- if someone else inserts the same key concurrently, -- we could get a unique-key failure
BEGIN
INSERT INTO test4(name,count) VALUES (key, data);
RETURN;
EXCEPTION WHEN unique_violation THEN-- do nothing, and loop to try the UPDATE again
END;
END LOOP;
END;
$$
LANGUAGE plpgsql;
謝謝,只是想弄清楚「X」是什麼?無法在文檔中找到它。 – evgeni 2011-03-03 19:17:17
X是一個表別名(Google)。在這種情況下,該表實際上是一個由子查詢形成的表表達式。 PostgreSQL和MySQL(至少)要求子查詢被命名。該語句可以寫成'select X.name,sum(X.cnt)...'。但是,由於我不使用別名,我只是給它一個虛擬名稱。 – Reece 2011-03-07 00:05:31