How to merge two mysql query results into one array?

You can use UNION operator to merge the result-set of two or more SELECT statements into one array.
The default behavior for UNION is that duplicate rows are removed from the result. UNION ALL does not remove duplicate.

There are few things need to be kept in mind.

A. SELECT statement within the UNION must have the same number of columns.
B. The field should have similar data types.
C. Fields in each SELECT statement must be in the same order if not make them.
D. If column have diffrent name make column another name by using an alias with “AS” kewords as given in the example

SELECT column1 AS alias_name FROM table

Here is the full example of UNION.


	  $select_btemp_1 = "SELECT * FROM table1 WHERE enable='1' AND aid='1'";

	  $select_btemp_2 = "SELECT * FROM table1 WHERE enable='1' AND user_id='$user_id' ORDER BY  aid ASC";

	  $select_btemp =  $select_btemp_1." ".UNION." ".$select_btemp_2;

	  $btemp_query = mysql_query($select_btemp);
	  $btemp_count = mysql_num_rows($btemp_query);

	  if($btemp_count > 0)
	  {
		while($row_images = mysql_fetch_array($btemp_query))
		{ 	
			echo $row_images[temp_desc];	
		}
	  }

	
Share

One thought on “How to merge two mysql query results into one array?

Leave a Reply

Your email address will not be published. Required fields are marked *