Home > Back-end >  How to save only one column in a SELECT statement with multiple fields?
How to save only one column in a SELECT statement with multiple fields?

Time:09-22

I am trying to build a SQL statement that selects 4 columns from a table but only saves one of them.

... UNION SELECT field1,field2,field3 INTO OUTFILE '/path' FROM table WHERE condition

The result is

field1,field2,field3

However I only want to save field3.

field3

I have tried:

 ... UNION SELECT NULL,NULL,field3 INTO OUTFILE '/path' FROM table WHERE condition

But it results on the follwing:

\n \n field3

I cannot remove the field1 and field2 because the SQL statement is to be concatenated with other SQL statements.

Thank you for your help

Note : I am using MySQL

CodePudding user response:

Make the main query a subquery before union.

SELECT field3 
FROM (
   {other SQL statements}
) other_sql_statements
UNION
SELECT field3 
INTO OUTFILE '/path' 
FROM table 
WHERE condition

In MySQL 8 with CTE:

WITH other_sql_statements AS (
   {other SQL statements}
)
SELECT field3
FROM other_sql_statements
UNION
SELECT field3 
INTO OUTFILE '/path' 
FROM table 
WHERE condition
  • Related