douzhi2012 2011-12-12 06:46
浏览 724
已采纳

如果第一个结果集为空,则SQL UNION不显示第二个结果集的结果

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.

  • 写回答

2条回答 默认 最新

  • doushichun9409 2011-12-12 06:52
    关注
    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退