【问题标题】:Creating a query to insert data into MySQL using foreign keys创建查询以使用外键将数据插入 MySQL
【发布时间】:2013-03-29 17:38:53
【问题描述】:

我是数据库的新手,我正在尝试将数据插入以下表格:

表格开始

表 = 用户

列 = id ,用户名,密码

表 = users_info

Columns = id , e-mail , address , logged , portrait , user_id

桌尾

users_info.user_id 是链接到 users.id 的外键。

我想构建一个查询,该查询将根据来自(users 表)的信息将数据插入(users_info 表)...文字即:

Insert portrait into users_info where user_id = users.id and username = JohnDoe

执行此操作的语法是什么?

谢谢!!

【问题讨论】:

  • 不,我想将数据插入到与 user_id = users.id 匹配的行的 users_info 中。这不是用于创建新条目或行,而是更新现有条目或行。是的,两个表上的 id 列都是 AUTO_INCREMENT 上的主键

标签: mysql sql sql-insert


【解决方案1】:

试试这个:

Insert portrait into users_info 
(id, email) VALUES ( select user.id, 'johndoe@domain.com' )
where user_id = users.id and username = 'JohnDoe'
)

【讨论】:

    【解决方案2】:

    如果您想要更新users_info 表中的数据,那么您必须使用 UPDATE 命令。

    UPDATE users_info a SET a.portrait = 'value1', a.logged = 'value2', a.address = 'value3', a.email = 'value4' where a.user_id = (SELECT DISTINCT(id) FROM users b WHERE b.username = 'JohnDoe')
    

    http://www.w3schools.com/sql/上的 SQL 命令基础

    祝你好运!

    【讨论】:

    • 非常棒,工作完美,感谢 LoBS。也感谢您提供 SQL 教程链接,我真的需要它。
    猜你喜欢
    • 2017-12-07
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 2018-07-30
    相关资源
    最近更新 更多