插入到多个列的select中,其中只有一列来自另一个表

时间:2014-03-04 13:10:57

标签: php mysql

在正确的SQL上挣扎。尝试将数据插入表中,但只需插入另一个表中的一列

INSERT INTO customer_details (user_id, firstName, lastName, email, mobile) 
VALUES (SELECT id FROM users WHERE username = ?, ?, ?, ?, ?');

使用以下“bind_param”函数,我将为变量分配变量

$stmt->bind_param('ssssi', $username, $first_name, $last_name, $email, $mobile_num);   

非常感谢!

4 个答案:

答案 0 :(得分:1)

您需要insert . . . select形式的insert

INSERT INTO customer_details (user_id, firstName, lastName, email, mobile)  
    SELECT id, ?, ?, ?, ?
    FROM users
    WHERE username = ?;

请注意,这会更改参数的顺序,因为where中的比较现在是最后一次。

答案 1 :(得分:1)

尝试13.2.5.1 INSERT ... SELECT Syntax

 
INSERT INTO 
    customer_details (user_id, firstName, lastName, email, mobile) 
SELECT id, ?, ?, ?, ? 
FROM users 
WHERE username = ?

编辑:检查以下示例以了解insert ..select的工作原理:

创建两个表:onetwo

mysql> CREATE TABLE one (x int, y int);
Query OK, 0 rows affected (0.58 sec)

mysql> CREATE TABLE two (x int, y int);
Query OK, 0 rows affected (0.22 sec)

在表two中插入了一些行:

mysql> INSERT INTO two (x, y)  VALUES (1, 2), (2, 4), (3, 5), (6, 7);
Query OK, 4 rows affected (0.19 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM `two`;
+------+------+
| x    | y    |
+------+------+
|    1 |    2 |
|    2 |    4 |
|    3 |    5 |
|    6 |    7 |
+------+------+
4 rows in set (0.03 sec)

one为空:

mysql> SELECT * FROM `one`;
Empty set (0.02 sec)

现在,在表one中插入表x中表one == y中的每个two,表中的y one等于变量的值(例如,脚本中来自用户的一些数据)。此外,如果条件为真,则tow的行将执行插入操作。

mysql> SET @a = 100;  -- variable 
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO one (x, y)  SELECT y, @a FROM two WHERE y IN (2, 4, 7) ;
Query OK, 3 rows affected (0.12 sec)
Records: 3  Duplicates: 0  Warnings: 0

现在表one是:

mysql> SELECT * FROM one;
+------+------+
| x    | y    |
+------+------+
|    2 |  100 |  -- 100 is like value from use not from table `two`
|    4 |  100 |
|    7 |  100 |
+------+------+
3 rows in set (0.00 sec)

答案 2 :(得分:0)

尚未对此进行测试,但请尝试:

INSERT INTO customer_details (user_id, firstName, lastName, email, mobile) 
(SELECT id,?, ?, ?, ? FROM users WHERE username = ?)

答案 3 :(得分:0)

也许:

INSERT INTO `customer_details` (`user_id`, `firstName`, `lastName`, `email`, `mobile`) 
SELECT `id`, ?, ?, ?, ? FROM `users` WHERE `username` = ?

$stmt->bind_param('ssssi', $first_name, $last_name, $email, $mobile_num, $username);