mysql中UNION使用的问题 --乐杨俊

本文详细介绍了如何使用 SQL 的 UNION 操作符来合并不同表中的数据,特别是当表间字段数量不一致时的处理方法。提供了具体的例子来说明如何正确地进行字段匹配。

总结问题:

a表中有x,y,z 3个字段,b表中只有x,y 2个字段,
我用union组合查询结果时应该怎样写?
(select * from a)
union 
(select (*,z) from b)     这样是不可以的

解答:
UNION 用于把来自许多SELECT语句的结果组合到一个结果集合中。(如果你要将多个表的查询结果进行合并输出比如说 群组消息跟个人消息表是分离的但是想一起提取出来并显示的话就可以如此处理。通过MySQLUNION联合查询出来即可;
你要union两个表,就必须满足这两个表的字段名字都是一样的才行。首先,你的B表字段只有x,y两个,(select (*,z) from b) 这样写就已经不对了,因为Z字段不存在,应该是(select (*,'' as z) from b)。
最好就改成:select x,y,z from a union select x,y,'' as z from b ,这样就OK啦!

譬如:
function getdateorders($innid,$begindate,$enddate)
{
    global $_SGLOBAL,$_SC;
    $str_begin=$begindate;
    $str_end=$enddate;
    
    $orderstatus=$_SC["innorder_orderstatus"]["new"];
    $checkinstatus=$_SC["checkin_itemstatus"]["checkedin"];
    
    
    $sql="select min(groupid) as gid, min(id) as id,innid as innid,checkindate as d,roomid as roomid,count(1) as c,case itemstatus when 1 then 'checkedin' when 2 then 'checkedout' end as type  from inn_checkin where (checkindate) between '$begindate' and '$enddate' and innid=$innid
            group by checkindate,roomid,innid
            union
            select '0' as gid,id,innid as innid,arrivedate as d,roomid as roomid,nights as c,'ordered' as type from inn_order where arrivedate>='$begindate' and arrivedate<'$enddate' and orderstatus='$orderstatus'
            order by gid,d";  
 
    //print($sql);        
    $query = $_SGLOBAL['db']->query($sql);
    while($value = $_SGLOBAL['db']->fetch_array($query)) {
        $return_arr[] = $value;
    }
    return $return_arr;
    
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值