Java Cross Join MySQL

Cross Join joins the two tables.

Java Cross Join MySQL

In this section we will read about how the two tables can be joined using cross join in MySQL. Here we will see cross joining using a simple example.

Cross Join in SQL joins two tables. These two tables are joined in such a way that the each row of first table is joined with the each row of second table. After cross joining the tables it produces the total rows as number of rows in first table * number of rows in second table.

You may use the cross join using SQL SELECT query. This query returns the products of rows or records from the two tables.

SELECT * FROM table1 CROSS JOIN table2;

An image given below demonstrate you the cross joining of two tables in graphical way.


Here an example is being given which will demonstrate you how to do cross join in Java using MySQL. In this example we will first create two different tables and then we will insert some bulk values in both tables and then we will create a Java class where will write the code for database connectivity and execute the SQL query. We will execute the SQL query for cross joining of two tables.

Create table 'country'

CREATE TABLE `country` (                  
           `countryName` varchar(15) DEFAULT NULL  
         ) ENGINE=InnoDB DEFAULT CHARSET=latin1

After inserting the value in the table 'country' table is look like as follows :

Create table 'fruitorder'

CREATE TABLE `fruitorder` (             
              `fruitName` varchar(15) DEFAULT NULL  
            ) ENGINE=InnoDB DEFAULT CHARSET=latin1

After inserting the value into the table 'fruitorder' table is look like as follows :

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class CrossJoinExample {

	public static void main(String args[])
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String driver = "com.mysql.jdbc.Driver";
		String user = "root";
		String password = "root";
		String url ="jdbc:mysql://localhost:3306/record";
		String sql = "select * from fruitorder cross join country";
			con = DriverManager.getConnection(url, user, password);
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			  String fruit = rs.getString("fruitName");
			  String country = rs.getString("countryName");
			  System.out.println(fruit+" \t     "+country);
		catch(ClassNotFoundException cnfe)
		catch(SQLException sqle)


When you will compile and execute the above example you will get the output as follows :

Download Source Code

Share on Google+Share on Google+

Java Cross Join MySQL

Posted on: August 10, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Java Cross Join MySQL  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image