简体   繁体   中英

SQL. Convert age to date of birth

I was surprised when I did not find any mention of converting age to DOB (date of birth). There are many answers about converting DOB to age, but not vice versa.

I have two digits (I able to convert them to any data type, even into DateTime.date (python-format)). How I can convert them to a full SQL date. It must be current_date - age (day and month are not important to me). It is preferable to do this by the database, not by the python.

DDL:

cursor.execute("""CREATE TABLE IF NOT EXISTS users(
id int AUTO_INCREMENT PRIMARY KEY,
user_id INTEGER NOT NULL UNIQUE,
goal VARCHAR(255) DEFAULT NULL,
age INTEGER DEFAULT NULL,
gender VARCHAR(255) DEFAULT NULL,
country VARCHAR(255) DEFAULT NULL,
city VARCHAR(255) DEFAULT NULL,
comment VARCHAR(255) DEFAULT NULL)""")

ps related questions Calculate Age in MySQL (InnoDb)

In MySQL 8.x you can use INTERVAL arithmetic. For example:

select current_date() - interval 42 year 

Result:

1978-05-21

In your case this could translate to:

select current_date() - interval age year from users;

See running example at DB Fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM