日期:2014-05-17  浏览次数:20523 次

怎样把两条SQL写成一条语句
select session.* from hacref.session,hacconf.user,hacconf.orgunit where session.username=user.username and user.ou_id=orgunit.id and (orgunit.ou_id&(select ou_id from hacconf.orgunit where id=4))=(select ou_id from hacconf.orgunit where id=4);
 
select session.* from hacref.session,hacconf.device,hacconf.orgunit where serverIP=device.ip and device.ou_id=orgunit.id and (orgunit.ou_id&(select ou_id from hacconf.orgunit where id=4))=(select ou_id from hacconf.orgunit where id=4);

有两条语句,分别根据username,serverTP过滤条件,我想实现两者同时过滤,直接两条件AND会是空,需要帮助

------解决方案--------------------
有是有这种语法,只是语句写的貌似不合理,特别是最后=(select ... where id=4)那段,比较危险,一旦没控制好,数据出现2条以上就报错了,而且两个查询的表都不一样,合并不了的,要么就用union all合起来。
------解决方案--------------------
union 本身就会过滤重复数据。还有except这些也是可以过滤重复数据的,不知道你要怎么过滤。你自己看看联机丛书
------解决方案--------------------
SQL code

SELECT A1.* 
FROM hacref.session AS A1 
JOIN hacconf.user AS A2 ON (A1.username=A2.username)
JOIN hacconf.orgunit AS A3 ON (A2.ou_id=A3.ID) 
JOIN hacconf.device AS A4 ON (A1.serverIP=A4.IP AND A4.OU_ID=A3.ID)

WHERE (A3.OU_ID & (select ou_id from hacconf.orgunit where id=4)) = 
(select ou_id from hacconf.orgunit where id=4)

------解决方案--------------------
首先是两条合并 考虑union 而不是or或者and 但从字意上理解就可以区别出来 使用union 必须将两个sql语句的 列数量保持一致 ,写代码细心很重要 ,