azad
azad

Reputation: 361

SQL UNION is not showing the results of 2nd result set if 1st result set is empty

I have joined two SQL Queries using SQL UNION Operator

Example:

$query1 = "SELECT * FROM employees WHERE emp_first_name LIKE '%Donald%'";

$query2 = "SELECT * FROM employees WHERE emp_last_name LIKE '%George%'";

$final_query = $query1 . " UNION " . $query2

When I Run this $final_query, it shows the results of both queries if the first query's result set is not empty. If the first query has empty result set there will be no result shown even if second query has some values in the database.

Can some one explain where is the problem.

Note: Don't suggest me the use of single query, i have a reason to use two queries.

Upvotes: 2

Views: 1462

Answers (2)

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35146

mysql> create table employees (emp_first_name varchar(255), emp_last_name varchar(255)); 

Query OK, 0 rows affected (0.01 sec)

mysql> insert into employees values ('hasan','khan'),('john','doe'); 

Query OK, 2 rows affected (0.00 sec) Records: 2 Duplicates: 0 Warnings: 0

mysql> select * from employees where emp_first_name like '%nothing%' union select * From employees where emp_last_name like '%doe%';

+----------------+---------------+ 
| emp_first_name | emp_last_name |
+----------------+---------------+ 
| john           | doe           |
+----------------+---------------+ 

1 row in set (0.00 sec)

Works fine for me. Either the query you posted is not the same as the one you're executing or you have problem in your code.

Upvotes: 1

Rashmi Kant Shrivastwa
Rashmi Kant Shrivastwa

Reputation: 1167

use

union all

in place of union

Upvotes: 0

Related Questions