INSERT with SELECT

2019-01-01 03:17发布

I have a query that inserts using a select:

INSERT INTO courses (name, location, gid) 
            SELECT name, location, gid 
              FROM courses 
             WHERE cid = $cid

Is it possible to only select "name,location" for the insert, and set gid to something else in the query?

6条回答
几人难应
2楼-- · 2019-01-01 03:58

I think your INSERT statement is wrong, see correct syntax: http://dev.mysql.com/doc/refman/5.1/en/insert.html

edit: as Andrew already pointed out...

查看更多
有味是清欢
3楼-- · 2019-01-01 04:00

The right Syntax for your query is:

INSERT INTO courses (name, location, gid) 
SELECT (name, location, gid) 
FROM courses 
WHERE cid = $cid
查看更多
孤独总比滥情好
4楼-- · 2019-01-01 04:09

Correct Syntax: select spelling was wrong

INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want' 
FROM courses 
WHERE cid = $ci 
查看更多
墨雨无痕
5楼-- · 2019-01-01 04:10

Sure, what do you want to use for the gid? a static value, PHP var, ...

A static value of 1234 could be like:

INSERT INTO courses (name, location, gid)
SELECT name, location, 1234
FROM courses
WHERE cid = $cid
查看更多
唯独是你
6楼-- · 2019-01-01 04:11

Yes, it is. You can write :

INSERT INTO courses (name, location, gid) 
SELECT name, location, 'whatever you want' 
FROM courses 
WHERE cid = $ci

or you can get values from another join of the select ...

查看更多
看淡一切
7楼-- · 2019-01-01 04:13

Yes, absolutely, but check your syntax.

INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM   courses
WHERE  cid = 2

You can put a constant of the same type as gid in its place, not just 1, of course. And, I just made up the cid value.

查看更多
登录 后发表回答