2

我在 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,但我不知道怎么做

4

4 回答 4

1

下面是示例替换语句

选择替换(

replace('性别 = 女性,年龄 = 32 岁,疾病 = 乙型肝炎:DOID:2043',' = ','="')

, ', ','",') + '"';

于 2013-06-06T06:11:55.867 回答
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演示

于 2013-06-06T06:13:07.443 回答
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;

这将是这样的,但再次,重新考虑你的设计。

于 2013-06-06T06:15:44.347 回答
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.
于 2013-06-06T06:18:17.223 回答