简体   繁体   English

如何在同一个mysql查询中SELECT + INSERT?

[英]How can I SELECT+INSERT in the same mysql query?

I have a php script that process keywords from a mysql table "keywords" (columns: id - keyword) and then it saves data into another table "data" (column: id[foreign key keywords.id] - dataname - datavalue). 我有一个PHP脚本处理来自mysql表“keywords”(列:id - keyword)的关键字然后它将数据保存到另一个表“data”(列:id [外键关键字.id] - dataname - datavalue)。

My problem is that when the script is ready to save the data I only have the keyword and not the id. 我的问题是,当脚本准备好保存数据时,我只有关键字而不是id。

So is there a way I can get the keyword id and save the data in one mysql query? 那么有一种方法可以获取关键字id并将数据保存在一个mysql查询中吗? (i mean without having to do something like SELECT id from keywords where keyword = keyword, and then run another query for the INSERT. (我的意思是不必像关键字=关键字的关键字那样执行SELECT id,然后为INSERT运行另一个查询。

If selecting and modification tables are different - you can use simple nested query: 如果选择和修改表不同 - 您可以使用简单的嵌套查询:

INSERT INTO `data` (`id`, `dataname`) VALUES
(
    (SELECT `id` FROM `keywords` WHERE `keyword` = 'keyworrrrrd'),
    'blabla'
)

or 要么

INSERT INTO `data` (`id`, `dataname`)
SELECT `id`, 'blabla' FROM `keywords` WHERE `keyword` = 'keyworrrrrd'

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

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