MySQL合并两表插入时出现Operand should contain 1 column(s)错误求助
解决INSERT语句的"Operand should contain 1 column(s)"错误
嘿,这个错误我太熟啦!你遇到的Operand should contain 1 column(s)问题,核心原因是你在SELECT语句里嵌套了两个返回多列的子查询,数据库根本没法把多列结果当成单个字段来处理~
你的语句问题出在哪?
你原来的写法里,把两个子查询用逗号隔开放在SELECT后面,相当于告诉数据库:"我要两个字段,第一个是这个子查询的结果,第二个是另一个子查询的结果"。但第一个子查询返回了11个字段,第二个返回了4个,数据库完全懵了——它不知道怎么把多列数据塞进一个字段里,所以抛出了这个错误。
正确的写法应该是这样
其实你不需要嵌套子查询,直接通过INNER JOIN关联两个表,然后一次性选出所有需要插入的字段就行,字段顺序要和INSERT INTO后面指定的列顺序完全对应:
INSERT INTO com_short ( category_id, media_folder_id, gallery_folder_id, status, important, bgPositioning, published_at, published_by, created_at, modified_at, title, slug, body, featured_image_file_id ) SELECT com_post.category_id, com_post.media_folder_id, com_post.gallery_folder_id, com_post.status, com_post.important, com_post.bgPositioning, com_post.published_at, com_post.published_by, com_post.created_at, com_post.modified_at, com_post_translation.title, com_post_translation.slug, com_post_translation.body, com_post_translation.featured_image_file_id FROM com_post INNER JOIN com_post_translation ON com_post.id = com_post_translation.post_id;
为什么这样能行?
INNER JOIN已经帮你把com_post和com_post_translation表通过post_id关联起来了,你可以直接从两个表中选取需要的字段,只要保证SELECT里的字段数量、顺序、类型和com_short表的列完全匹配,就能顺利完成合并插入操作。
内容的提问来源于stack exchange,提问作者John




