使用选择插入
我有一个使用 SELECT
语句进行插入的查询:
INSERT INTO courses (name, location, gid)
SELECT name, location, gid
FROM courses
WHERE cid = $cid
是否可以仅选择“名称、位置”进行插入,并将 gid
设置为查询中的其他内容?
I have a query that inserts using a SELECT
statement:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
是的,绝对可以,但请检查你的语法。
您可以在其位置放置一个与 gid 相同类型的常量,当然不仅仅是 1。而且,我刚刚编写了
cid
值。Yes, absolutely, but check your syntax.
You can put a constant of the same type as
gid
in its place, not just 1, of course. And, I just made up thecid
value.是的。您可以编写:
或者您可以从 select 的另一个连接获取值...
Yes, it is. You can write :
or you can get values from another join of the select ...
正确语法:选择拼写错误
Correct Syntax: select spelling was wrong
当然,你想用 gid 做什么?静态值,PHP var,...
静态值 1234 可能类似于:
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 SELECT
语句从一个表复制数据并将其插入到另一个表中并且要求源表和目标表中的数据类型匹配。如果给定表列中的数据类型不匹配(即尝试将VARCHAR
插入INT
中,或将TINYINT
插入INT
中>) MySQL 服务器将抛出SQL 错误 (1366)
。所以要小心。
以下是该命令的语法:
旁注:有一种方法可以通过使用 在
SELECT
中进行转换,例如:此转换(
CAST()
是CONVERT( )
) 如果您的表在同一表列上具有不同的字符集(如果处理不当,可能会导致数据丢失),则非常有用。Of course you can.
One thing should be noted however: The
INSERT INTO SELECT
statement copies data from one table and inserts it into another table AND requires that data types in source and target tables match. If data types from given table columns does not match (i.e. trying to insertVARCHAR
intoINT
, orTINYINT
intoINT
) the MySQL server will throw anSQL Error (1366)
.So be careful.
Here is the syntax of the command:
Side note: There is a way to circumvent different column types insertion problem by using casting in your
SELECT
, for example:This conversion (
CAST()
is synonym ofCONVERT()
) is very useful if your tables have different character sets on the same table column (which can potentially lead to data loss if not handled properly).我们都知道这有效。
===========================
如果有多个“select”语句,可以使用以下方法。仅供参考。
We all know this works.
===========================
Below method can be used in case of multiple "select" statements. Just for information.
您的查询的正确语法是:
The right Syntax for your query is: