MYSQL INSERT SELECT 问题

2021-12-19 00:00:00 select insert mysql

我在理解如何执行某些 INSERT SELECT 方面有点困难.

i have a little difficulty in understanding how to do some INSERT SELECT.

例如我有两张桌子.

TABLE : users  

 id | name   | gender  
 1  | John   | m  
 2  | Mary   | f  

TABLE : website  

 fid | url             | id  
 1   | www.desilva.biz | 2  
 2   | gidhelp.com     | 4  

现在假设我想向表格网站添加另一个查询.我得到两个变量,让我们说:

Now let's say i want to add another query to the table website. I get two variables, lets say:

$user = John;
$site = "www.google.com";

我想从 users 表中选择 John 的 id 并在一个语句中将其插入到 website 表中.

i want to select the id of John from users table and insert it into website table in one statement.

我该怎么做?

推荐答案

假设你的变量已经被正确转义并且不受SQL注入的影响:

Assuming your variables are already escaped properly and are not subject to SQL injection:

INSERT
INTO    website (url, fid)
SELECT  $site, id
FROM    users
WHERE   name = $user

相关文章