Home  >  Q&A  >  body text

Mariadb troubleshooting using UNION's CREATE TABLE SELECT

<p>I'm working on a PHP script that contains six UNION SELECTs, and within the script this command runs just fine. This command also works fine when executed from a SQL client. However, when I try to put the SELECT statement inside the CREATE TABLE mytable SELECT, I get the following error message: </p> <pre class="brush:php;toolbar:false;">Incorrect column name ''</pre> <p>In five of the six UNION SELECT fragments, there is a column name named '', which is used as a placeholder when filling in data in subsequent parts of the script. But in one of the UNIONs, the same position is a varchar(32) column. <br /><br />It seems that the existence of an "anonymous" column does not matter in the normal execution of the command. But in the CREATE TABLE version, it doesn't like this. <br /><br />Why do SELECT and CREATE TABLE SELECT have different rules for union column names? </p><p><br /></p>
P粉115840076P粉115840076417 days ago503

reply all(1)I'll reply

  • P粉821231319

    P粉8212313192023-08-03 09:31:45

    Tables cannot contain blank or missing column names, while result sets can. The CREATE TABLE SELECT statement obtains the column names of the table from the result set of the SELECT statement. Therefore, you need to ensure that each column of the result set has a name, either derived from a column in some table or specified via an AS alias. For example,

    SELECT 'one' AS tablename, cola, colb, colc FROM table_one
     UNION ALL
    SELECT 'two',              cola, colb, colc FROM table_two
     UNION ALL
    SELECT 'three',            cola, colb, colc FROM table_three
    

    applies to the CREATE TABLE statement, while

    SELECT 'one',   cola, colb, colc FROM table_one
     UNION ALL
    SELECT 'two',   cola, colb, colc FROM table_two
     UNION ALL
    SELECT 'three', cola, colb, colc FROM table_three
    

    does not apply because it does not assign an alias column name to the first column.

    reply
    0
  • Cancelreply