[英]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列title
和content
添加到临时表中。 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
:您可以使用带有
TRIM
的SPACE
获得一个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
列的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.