【问题标题】:Inserting new data in a table在表中插入新数据
【发布时间】:2021-12-04 15:07:05
【问题描述】:

我创建了一个用于学习目的的基本表。

CREATE TABLE friends (
  id INT,
  name TEXT,
  birthday DATE
);

添加了一些数据...

INSERT INTO friends (id,name,birthday)
VALUES (1,'Jo Monro','1948-05-30');

INSERT INTO friends (id,name,birthday)
VALUES (2, 'Lara Johnson','1970-03-03');

INSERT INTO friends (id,name,birthday)
VALUES (3,'Bob Parker', '1962-09-3');

我意识到我忘了包括电子邮件列。 我添加了专栏...

ALTER TABLE friends
ADD COLUMN email;

..但是我现在如何才能只将数据添加到这个新列?

我尝试过 WHERE 语句,用和不用其他列名重写 INSERT INTO 语句,但没有任何效果?

我在这里错过了什么?

谢谢!

【问题讨论】:

  • 不能选择更新吗? UPDATE friends SET email = 'Jo.Monro@gmail.com' WHERE id = 1
  • 创建另一张表map_user_email,里面有对应人的id和email,然后使用update查询从map_user_email更新好友设置email使用update friends f, map_user_email m set f.email = m.mail Where f.id = m.id

标签: mysql sql sql-insert


【解决方案1】:

将电子邮件插入临时表,然后用它更新真实表。

CREATE TABLE friends (
  id INT auto_increment primary key,
  name VARCHAR(100),
  birthday DATE
);

INSERT INTO friends (name, birthday) VALUES 
  ('Jo Monro','1948-05-30')
, ('Lara Johnson','1970-03-03')
, ('Bob Parker', '1962-09-3');

ALTER TABLE friends ADD COLUMN email VARCHAR(100);

select * from friends
编号 |姓名 |生日 |电子邮件 -: | :----------- | :--------- | :---- 1 |乔梦露 | 1948-05-30 | 2 |劳拉·约翰逊 | 1970-03-03 | 3 |鲍勃·帕克 | 1962-09-03 |
--
-- temporary table for the emails
--
CREATE TEMPORARY TABLE tmpEmails (
 name varchar(100) primary key,
 email varchar(100)
);
--
-- fill the temp
--
insert into tmpEmails (name, email) values
  ('Jo Monro','jo.monro@unmail.net')
, ('Lara Johnson','lara.johnson@unmail.net')
, ('Bob Parker', 'UltimateLordOfDarkness@chuni.byo');
--
-- update the real table
--
update friends friend
join tmpEmails tmp
  on friend.name = tmp.name
set friend.email = tmp.email
where friend.email is null;
select * from friends
编号 |姓名 |生日 |电子邮件 -: | :----------- | :--------- | :-------------------------------- 1 |乔梦露 | 1948-05-30 | jo.monro@unmail.net 2 |劳拉·约翰逊 | 1970-03-03 | lara.johnson@unmail.net 3 |鲍勃·帕克 | 1962-09-03 | UltimateLordOfDarkness@chuni.byo

db小提琴here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 2016-08-06
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    相关资源
    最近更新 更多