Home >Database >Mysql Tutorial >How Can I UNION Database Tables with Different Numbers of Columns?
Merge tables with different number of columns
Challenges may be encountered when trying to merge database tables with different number of columns. A straightforward approach is to append null values to missing columns in tables with fewer columns.
For example, consider two tables, Table A and Table B, where Table A has more columns than Table B. In order to merge these tables while handling the missing columns in table B, follow these steps:
The following SQL query demonstrates this process:
<code class="language-sql">SELECT Col1, Col2, Col3, Col4, Col5 FROM Table1 UNION SELECT Col1, Col2, Col3, NULL AS Col4, NULL AS Col5 FROM Table2;</code>
In this query, "Col4" and "Col5" are missing columns in table B and are filled with null values in the UNION clause. Therefore, the UNION operation will merge the two tables seamlessly and leave missing column values as null.
The above is the detailed content of How Can I UNION Database Tables with Different Numbers of Columns?. For more information, please follow other related articles on the PHP Chinese website!