简体   繁体   English

是否可以从 select 查询创建一个临时表并同时添加一组额外的列?

[英]Is it possible to create a temporary table from a select query AND add a set of extra columns at the same time?

I want to create a temporary table in one line using 3 columns + content from a existing table called affiliateproduct and at the same time add 2 columns title and content to the temporary table.我想在一个名为affiliateproduct的现有表中使用3列+内容在一行中创建一个临时表,同时将2列titlecontent添加到临时表中。 Both need to be of type VARCHAR, however i cannot define these 2 columns explicitly in the same query.两者都需要是 VARCHAR 类型,但是我不能在同一个查询中明确定义这 2 列。 As a workaround i did the following:作为一种解决方法,我做了以下事情:

       CREATE TEMPORARY TABLE affiliate_product_results ENGINE = MEMORY SELECT ap.id,
           ap.affiliateImageUrl, ap.rank, "" AS title, "" AS content FROM affiliateproduct ap; 

This results in a table that includes the 3 columns from affiliateproduct with corresponding types, but title and content both get the type char(0) assigned.这会生成一个表,其中包含来自affiliateproduct 的3 列具有相应类型,但标题和内容都获得分配的类型char(0) That is not the type that i want.那不是我想要的类型。 (It should be varchar(255) instead). (它应该是varchar(255)代替)。 Is there a way to get this to work with the correct type assignment?有没有办法让它与正确的类型分配一起工作? (I know i could probably assign a value of " " or something and then it would become a varchar(n spaces) but thats rather hacky. (我知道我可能会分配一个" "或其他东西的值,然后它会变成一个 varchar(n 个空格),但这很hacky。

Is there a way or am i forced to do an extra column insert query after the temporary table creation.有没有办法或者我在临时表创建后被迫做一个额外的列插入查询。

Thank you.谢谢你。

EDIT: I found a way to do it but its hacky.编辑:我找到了一种方法,但它很老套。 It goes like this:它是这样的:

       CREATE TEMPORARY TABLE affiliate_product_results ENGINE = MEMORY SELECT ap.id,
           ap.affiliateImageUrl, ap.rank, ap.affiliateImageUrl AS title, ap.affiliateImageUrl AS content FROM affiliateproduct ap; 

Now title and content get the same columntype as affiliateimageUrl (varchar255)现在标题和内容获得与affiliateimageUrl(varchar255)相同的列类型

You can get a VARCHAR column using SPACE with TRIM :您可以使用带有TRIMSPACE获得一个VARCHAR列:

CREATE TEMPORARY TABLE affiliate_product_results ENGINE = MEMORY 
SELECT ap.id, ap.affiliateImageUrl, ap.rank, 
  TRIM(SPACE(255)) AS title, 
  TRIM(SPACE(255)) AS content
FROM affiliateproduct

In case you want to initialize the new VARCHAR columns with NULL :如果您想使用NULL初始化新的VARCHAR列:

CREATE TEMPORARY TABLE affiliate_product_results ENGINE = MEMORY 
SELECT ap.id, ap.affiliateImageUrl, ap.rank, 
  IF(TRIM(SPACE(255)) = '', NULL, TRIM(SPACE(255))) AS title, 
  IF(TRIM(SPACE(255)) = '', NULL, TRIM(SPACE(255))) AS content
FROM affiliateproduct

You can adjust the size of the VARCHAR column with the parameter on SPACE .您可以使用SPACE上的参数调整VARCHAR列的大小。

demo on dbfiddle.uk dbfiddle.uk 上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM