【问题标题】:How To split and update column at the same time in Mysql?如何在Mysql中同时拆分和更新列?
【发布时间】:2022-11-22 21:53:26
【问题描述】:

我正在为我的作品集做一个迷你项目。除了有一个列名外,这是完成的尺寸哪个包含整数空间和字母.例如

size    

3 ABC

4 XYZ

19 pqr

.

.

我想通过删除字母来更新此表,使其看起来像这样

size

3

4

19

.

.

我尝试了不同的方法,这基本上给了我语法错误。

alter table bengaluru_house_prices
modify column size substring_index(size, ' ' , 1);



alter table bengaluru_house_prices
modify column size integer;

谢谢

【问题讨论】:

  • 如果你有 3 ABC4 怎么办?
  • @ErgestBasha 然后我只想检索 3。
  • 这回答了你的问题了吗? Cast from VARCHAR to INT - MySQL
  • 你的专栏吗总是从数值开始?
  • UPDATE <table> SET <column> = CAST(<table>.<column> AS UNSIGNED ) WHERE ....

标签: mysql ddl


【解决方案1】:

如果您只喜欢起始整数,则可以使用 REGEXP_SUBSTR。

考虑以下数据。

CREATE TABLE bengaluru_house_prices (
 size varchar(20) );

insert into bengaluru_house_prices values ('3 ABC'),('3 ABC 4'),('4 XYZ'),('19 pqr'),('.'),('.'),('19 pqr25');

选择,

select REGEXP_SUBSTR(size,"[0-9]+") as new_size 
from bengaluru_house_prices;

结果:

new_size
3
3
4
19
null
null
19

要更新表格,我建议创建另一列然后更新它并在最后删除它

SET autocommit=0;
LOCK TABLES bengaluru_house_prices WRITE;
alter table bengaluru_house_prices add column new_size int default null;
update bengaluru_house_prices 
set new_size = REGEXP_SUBSTR(size,"[0-9]+") ;
alter table bengaluru_house_prices drop column size ;
COMMIT;
UNLOCK TABLES;

https://dbfiddle.uk/2oMqufmi

【讨论】:

    猜你喜欢
    • 2016-03-01
    • 2012-05-29
    • 2023-02-23
    • 2018-12-29
    • 2013-09-18
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多