9

是否基于 MySQL 中可能的列之一上的选择进行插入

INSERT INTO student_fees(id, name, fees) 
VALUES(1, SELECT name from students where student_id = 1, 200$) 

如果是,那么示例将真正有帮助。

-谢谢

4

3 回答 3

11

尝试INSERT...SELECT声明

INSERT INTO student_fees(id, name, fees) 
SELECT ... -- put here the SELECT STATEMENT with condition

如果您的列IDauto incremented,则不必指定 ,1否则会导致错误。

INSERT INTO student_fees(name, fees) 
SELECT `name`, '200$' 
FROM students         -- this will select all students on the table
                      -- and add $200 on thier fees.

另一点是,如果你只想从student's 表中插入一列,你需要指定条件,这样你就不会得到约束错误(假设你的列 ID 是主键

INSERT INTO student_fees(name, fees) 
SELECT `name`, '200$' 
FROM   students
WHERE  columnName = 'blahBlah'

更新 1

看到你的评论,你有这个查询

INSERT INTO coupon_allotment (page_id, offer_id, coupon_code, user_id) 
SELECT page_id, 4, 'ABC'        -- number of columns mismatch, right?
FROM pages_discounts_association 
WHERE discount_id = 4

you need to remove the user_id column above OR you need to add an ID in your select statement in order to match the number of columns.

于 2012-08-10T09:10:04.003 回答
3

只需使用常规INSERT INTO ... SELECT语法并选择其他字段作为常量,如下所示:

INSERT INTO student_fees(id, name, fees) 
SELECT 1, `name`, '200$' FROM students
于 2012-08-10T09:09:39.327 回答
2

试试这个:

INSERT INTO student_fees(id, name, fees) 
Select 1, name,'200$' from students 
于 2012-08-10T09:09:41.433 回答