MySQL 使用内部联接插入查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17666443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:10:35  来源:igfitidea点击:

Insert query with an inner join

mysql

提问by Sir

I want to make my insert query which has an inner join to a user's data table.

我想让我的插入查询与用户的数据表有一个内部连接。

The example of the tables is like this:

表的例子是这样的:

users:

users:

uid | name 


users_data:

users_data:

id | data_id | uid | other fields


data_stocks

data_stocks

id | data_id | quantity


So im trying to insert into data_stocksrelating to only knowing the uidfrom users.

所以我试图插入data_stocks只知道uidfrom 的相关信息users

Kinda of like this:

有点像这样:

INSERT INTO data_stocks (data_id,quantity)
VALUES (' need to join it some how ','$quantity');

Is this possible in mySQL?

这在 mySQL 中可能吗?

回答by Gordon Linoff

You want to use the insert ... selectform of the statement:

你想使用insert ... select语句的形式:

INSERT INTO data_stocks (data_id,quantity)
    select ud.data_id, $quantity
    from users u join
         users_data ud
         on u.uid = ud.uid;

If you are doing this for only one user, it might look more like this:

如果您只为一位用户执行此操作,则它可能看起来更像这样:

INSERT INTO data_stocks (data_id,quantity)
    select ud.data_id, $quantity
    from users_data ud
    where ud.uid = $uid;