简体   繁体   English

MYSQL 从 Table1 获取 id 并在插入值时插入到 Table2(用户表单)

[英]MYSQL Get id from Table1 and Insert to Table2 while INSERTING Values (USER Form)

I have 2 tables:我有 2 张桌子:

Table1表格1

u_id    email
1       user1@y.com
2       user2@h.com

and Table2和表2

id u_id values

had to insert values to table2 with u_id when user enters from form Example:I need to add the value table1 u_id while that user is logged in into table2 that is id increments in table and u_id from table1 and values as user enters from table2当用户从表单输入时,必须使用 u_id 将值插入 table2 示例:我需要在该用户登录到 table2 时添加值 table1 u_id,即 table1 中的 id 增量和 table1 中的 u_id 以及用户从 table2 输入时的值

i tried something this query however not successful我尝试了这个查询但没有成功

insert into table2 (u_id,values)
            values ((select u_id from table1), 'values')

The problem with your query is that the subquery returns multiple rows (one value per row in table1 ), while the database expects a scalar value.您的查询的问题是子查询返回多行( table1中的每行一个值),而数据库需要一个标量值。

I would expect that you know the email of the current user, and want to recover the corresponding u_id to insert a new row in table2 , along with a literal value.我希望您知道当前用户的email ,并希望恢复相应的u_id以在table2insert新行以及文字值。 If so, I would recommend the insert... select syntax:如果是这样,我会推荐insert... select语法:

insert into table2 (u_id, val)
select u_id, 'foo' from table1 where email = 'user1@y.com'

Side note: values is a SQL keyword, hence not a good choice for a column name (you would need to quote this identifier every time you use it).旁注: values是一个 SQL 关键字,因此不是列名的好选择(每次使用时都需要引用此标识符)。 I renamed this column to val in the query.我在查询中将此列重命名为val

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MySQL:使用 id 将 table2 中的条目与 table1 中的条目匹配,然后将匹配项作为新列插入 table2 - MySQL: Match entry in table2 to those in table1 using an id, then insert matches as new column into table2 MySQL用CASE从表2值更新表1 - Mysql Update table1 from table2 values with CASE 从table1插入或替换到table2 - insert or replace into table2 from table1 将table2中每个元素的值添加到table1中,并将table1中的MAX(id)+1用作table2 id - Add values to table1 for each element from table2 and using MAX(id) + 1 from table1 as table2 id 从table1获取多个值,将其更改为基于table2的值,然后将结果写入table1 - get multiple values from table1, change them to values based on table2 and write the result to table1 如何从表2中获取具有发送者和接收者名称的所有数据,这些名称与user(table1)表中的id链接 - how to get all data from table2 with sender and receiver name which linked with id from user(table1) table 如果table1.value1不等于table2.value1,MYSQL将数据从table1插入table2 - MYSQL insert data into table2 from table1, provided that table1.value1 is not equal table2.value1 SQL - 如果表 1 中存在 id,则将记录插入表 2 - SQL - If id exists in table1, then insert record into table2 从表1,表2中选择*,其中表1.ID = 1,显示具有其他ID的值 - select * from table1, table2 where table1.id = 1 showing values with other id MySQL触发器-在table1中插入时更新table2 - MySQL trigger - Update table2 on insert in table1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM