PSQL选择&替换字符

时间:2016-10-18 16:41:34

标签: psql

如何根据不同菜单中的名称从两个表中进行选择,但PSQL中的数据几乎相同? 我尝试过使用psql命令中的select和replace。

SELECT * FROM americanmenu JOIN europeanmenu ON replace(usmenu.type, \'US\', \'EU\') = eumenu.type WHERE usmenu.type = eumenu.type    

表格美国

ID | type | year  
----------------------
01 |  wine 1 us |  2001  
02 | wine 2  us | 2002

表格EU

ID | TYPE | year
--------------------
01 | wine 1 eu | 2001  
02 | wine 2 eu | 2002

我还没有列出额外的价格和口味等级列,因为这是问题的要点。我想按类型从us表中选择,并将最后2个字符/字符串替换为“eu”,并且能够比较两个表,即使有很多相同的数据。谢谢!

1 个答案:

答案 0 :(得分:0)

查询:

t=# SELECT *
FROM americanmenu a
JOIN europeanmenu e ON replace(a.type, 'us','eu') = e.type;
 id  |    type     | year | id  |    type     | year
-----+-------------+------+-----+-------------+------
 01  |  wine 1 us  | 2001 | 01  |  wine 1 eu  | 2001
 02  |  wine 2 us  | 2002 | 02  |  wine 2 eu  | 2002
(2 rows)

Time: 0.297 ms

制备

t=# create table americanmenu (id text, type text, year int);
CREATE TABLE
Time: 4.515 ms
t=# create table europeanmenu (id text, type text, year int);
CREATE TABLE
Time: 15.218 ms
t=# copy americanmenu from stdin delimiter '|';
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> 01 | wine 1 us | 2001
02 | wine 2 us | 2002>>
>> \.
COPY 2
Time: 7144.563 ms
t=# copy europeanmenu from stdin delimiter '|';
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> 01 | wine 1 eu | 2001
02 | wine 2 eu | 2002>>
>> \.
COPY 2
Time: 9729.000 ms