Thursday, September 13, 2012

SQL UNION Operator


MySQL UNION Operator 

You can use union if you want to select rows one after the other from several tables, or several sets of rows from a single table all as a single result set.This is actually merging 2 or more tables having columns of same data type.
Create following 2 tables in my_database for this example of codes

CREATE TABLE IF NOT EXISTS `emp_name` (
  `id` int(40) NOT NULL AUTO_INCREMENT,
  `name` varchar(40) NOT NULL,
  `country` varchar(40) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `emp_name`
--

INSERT INTO `emp_name` (`id`, `name`, `country`) VALUES
(1, 'Oksana Bebiac', 'Ukrane'),
(2, 'Larisa Volk', 'Ukrane'),
(3, 'Ruth Allon', 'USA'),
(4, 'Kylee Nguyen', 'Japan');
CREATE TABLE IF NOT EXISTS `emp_name2` (
  `id` int(30) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `country` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `emp_name2`
--

INSERT INTO `emp_name2` (`id`, `name`, `country`) VALUES
(1, 'Oksana Bebiak', 'Ukrane'),
(2, 'Anlen Jozz', 'Ukrane'),
(3, 'Eshe Biabaku', 'USA'),
(4, 'Lizza Diction', 'Japan');

Then Create following PHP codes to union tables emp_name and emp_name2

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_database", $con);

$result = mysql_query("SELECT name FROM emp_name UNION SELECT name FROM emp_name2");

echo "<table border='1'>
<tr>
<th>Name</th>
</tr>";
while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['name'] . "</td>";
 echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>


Name
Oksana Bebiak
Larisa Volk
Ruth Allon
Kylee Nguyen
Anlen Jozz
Eshe Biabaku
Lizza Diction

You may have noticed there are two Okasana Babiak in two tables but displays only one This will be resolved by using UNION ALL operator instead of UNION.

No comments:

Post a Comment