当我在列中混合数据(如 varchar 和 Integer)时,将我的多个列连接到日期时间的最佳方法是什么?

What's the best way to concat my multiple columns into datetime, when I have mixed data in columns, like both varchar and Integer?

所以数据是 table,日期和时间信息分为 4 列,一些是 varchar,其他是整数:

Year   Month   Day   Time
2022   May     20    18:43
1982   Feb     01    00:23
1942   Jan     13    16:17

月和时间为varchar,年和日为整数。

我必须通过 MYSQL 进行查询才能找到某些日期,如果我搜索的字段是像“2022-05-20 18:43”

这样的日期时间,那就更容易了

我昨天搜索了一整天,找到了很多接近我需要但不完全适合的示例,我对 MYSQL 的理解还不够好。

我假设我必须在某些时候使用 concat(),但是我必须对 varchar 进行转换

我想 运行 一个在数据库中创建新列的查询,它是日期时间,然后我可以直接查询。因此,创建一个名为 'date2' 的新列,它是我已经创建的日期时间,只需以某种方式连接,然后将每一行数据移动到它。像这样:

Year   Month   Day   Time    Date2
2022   May     20    18:43   2022-05-20 18:43
1982   Feb     01    00:23   1982-02-01 00:23
1942   Jan     13    16:17   1942-01013 16:17

这是 Table 架构:

CREATE TABLE `lunar2` (
  `year` int(4) unsigned NOT NULL,
  `month` varchar(3) NOT NULL,
  `day` int(2) NOT NULL,
  `time` time NOT NULL,
  `sign` varchar(15) NOT NULL,
  `other` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1

这是有效的代码。感谢提供代码的人:

UPDATE table1 SET
other =  STR_TO_DATE(CONCAT_WS(' ', Year, Month, Day, Time), '%Y %M %d %H:%i:%s');

尝试使用 STR_TO_DATE() 创建一个 DATETIME 值。

ALTER TABLE yourTable ADD COLUMN Date2 DATETIME;

UPDATE yourTable SET
    Date2 = STR_TO_DATE(CONCAT_WS(' ', Year, Month, Day, Time), '%Y %b %d %H:%i:%s');

更新:由于您的 Time 字段实际上是 TIME 类型,因此我们需要使用 %H:%i:%s 来正确解析它。

这是您尝试执行的操作的示例。
将字符串转换为日期时,正确设置格式字符串很重要,否则我们会得到一个空值。

create table datess(
y int,
m varchar(3),   
d int,
t varchar(5));
insert into datess (y,m,d,t)values
(2022 ,'May',  20    ,'18:43'),
(1982 ,'Feb',  01    ,'00:23'),
(1942 ,'Jan',  13    ,'16:17');
SELECT 
  STR_TO_DATE(
  CONCAT(y,'-',m,'-',d,' ',t),
  '%Y-%M-%d %H:%i') date_format
FROM datess;
| date_format         |
| :------------------ |
| 2022-05-20 18:43:00 |
| 1982-02-01 00:23:00 |
| 1942-01-13 16:17:00 |

db<>fiddle here