我在postgresql数据库示例表s_attrs属性中有很多记录,如
sex = female, age = 32 years, disease = hepatitis B:DOID:2043
sex = male, age = 35 years, disease = hepatitis B:DOID:2043
sex = male, age = 34 years, disease = hepatitis B:DOID:2043
sex = male, age = 55 years, disease = hepatitis B:DOID:2043
sex = male, age = 37 years, disease = hepatitis B:DOID:2043
sex = female, age = 31 years, disease = hepatitis B:DOID:2043
我想将其改为喜欢
sex="female", age="32 years", disease="hepatitis B:DOID:2043"
sex="male", age="35 years", disease="hepatitis B:DOID:2043"
sex="male", age="34 years", disease="hepatitis B:DOID:2043"
sex="male", age="55 years", disease="hepatitis B:DOID:2043"
sex="male", age="37 years", disease="hepatitis B:DOID:2043"
sex="female", age="31 years", disease="hepatitis B:DOID:2043"
删除等号之间的空格并添加引号, 我怎样才能改变它。我想使用更新并替换sql,但我不知道该怎么做
答案 0 :(得分:1)
下面是示例替换语句
选择替换(
替换('性别=女性,年龄= 32岁,疾病=乙型肝炎:DOID:2043','=','='')
,',','“,')+'”';
答案 1 :(得分:1)
假设您的表中有一个id列,您的基本查询可能如下所示
WITH attr_explode AS
(
SELECT id, unnest(string_to_array(s_attrs, ',')) attr
FROM Table1
)
SELECT id, array_to_string(array_agg(concat(trim(split_part(attr, '=', 1)), '="', trim(split_part(attr, '=', 2)), '"')), ',') s_attrs
FROM attr_explode
GROUP BY id
输出:
| ID | S_ATTRS |
--------------------------------------------------------------------
| 1 | sex="female",age="32 years",disease="hepatitis B:DOID:2043" |
| 2 | sex="male",age="35 years",disease="hepatitis B:DOID:2043" |
...
这是 SQLFiddle 演示
现在更新你可以做到
WITH attr_explode AS
(
SELECT id, unnest(string_to_array(s_attrs, ',')) attr
FROM Table1
), attr_replace AS
(
SELECT id, array_to_string(array_agg(concat(trim(split_part(attr, '=', 1)), '="', trim(split_part(attr, '=', 2)), '"')), ',') s_attrs
FROM attr_explode
GROUP BY id
)
UPDATE Table1 t
SET s_attrs = r.s_attrs
FROM attr_replace r
WHERE t.id = r.id
这是 SQLFiddle 演示
答案 2 :(得分:0)
您是否在表格的一列中拥有所有这些信息?
因为如果是这样,您可能希望将您的设计更改为3列: 性别,年龄,疾病。
无论如何,如果你想改变这个,那就像是:
UPDATE REPLACE(column_name, ',' , '",') FROM table_name WHERE condition;
UPDATE REPLACE(column_name, '= ' , '="') FROM table_name WHERE condition;
UPDATE CONCAT(column_name, '"' ) FROM table_name WHERE condition;
这将是这样的,但同样重新考虑你的设计。
答案 3 :(得分:0)
$str="sex = female, age = 32 years, disease = hepatitis B:DOID:2043";
$str=str_replace(" = ","=",$str);
//echo $str;
$str=str_replace('=','="', $str);
//echo $str;
$str=str_replace(',','",', $str);
echo $str.'"';
Find this is an Example. It may useful for your need.