是否根据MySQL中可能的列之一选择插入
INSERT INTO student_fees(id, name, fees)
VALUES(1, SELECT name from students where student_id = 1, 200$)
如果是,则示例将真正有用。
-Thanks
答案 0 :(得分:10)
尝试INSERT...SELECT
声明
INSERT INTO student_fees(id, name, fees)
SELECT ... -- put here the SELECT STATEMENT with condition
如果您的专栏ID
为auto 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
表中插入一列,则需要指定条件,这样就不会出现约束错误(假设您的列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
您需要删除上面的user_id
列,或者您需要在您的select语句中添加 ID
以匹配该数字列。
答案 1 :(得分:3)
只需使用常规INSERT INTO ... SELECT
语法,并选择其他字段作为常量,如下所示:
INSERT INTO student_fees(id, name, fees)
SELECT 1, `name`, '200$' FROM students
答案 2 :(得分:2)
试试这个:
INSERT INTO student_fees(id, name, fees)
Select 1, name,'200$' from students