2012-03-31 78 views
-1

我有如下因素MySQL查询,并试图右外连接,但无法understan如何做到这一点外部联接在MySQL Qyery

这里查询plase任何一个帮助

select lp_des.lpname,today.cnt_veh_tdy,todate.cnt_veh_tdate 
from 
(select distinct registration.lpcode,loadingpoint.lpname 
from registration,loadingpoint 
where registration.lpcode=loadingpoint.lpcode) lp_des, 
(select lpcode,count(vehicleno) cnt_veh_tdate 
from registration 
where registration.companycode='01' 
group by lpcode) todate, 
(
select lpcode,count(vehicleno) cnt_veh_tdy 
from registration 
where registration.companycode='01' 
and registration.date=(select max(date) from registration) 
group by lpcode) today 
right outer join today on lp_des.lpcode = today.lpcode 
right outer join todate on lp_des.lpcode = todate.lpcode 

我想做出正确的外连接的这部分

where lp_des.lpcode=todate.lpcode 
and lp_des.lpcode=today.lpcode 

请提前感谢

+1

它是否必须是“正确的外部连接”?也许你应该描述你想要的结果,而不是只发布你认为需要的解决方案。 – GolezTrol 2012-03-31 06:49:40

+0

此外,关于整个世界使用'左join'(='左外join')。每一个正确的加入对A和B可以改写为左连接B和A,这使得它更具可读性。特别是在一个查询中混合正确的连接和左连接使得读取,测试和修改变得更加困难。 – GolezTrol 2012-03-31 06:51:56

+0

我做了右外连接在上面的查询请立即赤什么可能是语法错误在查询 – 2012-03-31 06:51:57

回答

0

你问这个:

select 
    lp_des.lpname, 
    today.cnt_veh_tdy, 
    todate.cnt_veh_tdate 
from 
    (select distinct 
    r.lpcode, 
    l.lpname 
    from 
    registration r 
    inner join loadingpoint l on l.lpcode = r.lpcode) lp_des 
    right join 
    (select 
     r.lpcode, 
     count(r.vehicleno) cnt_veh_tdate 
    from 
     registration r 
    where 
     r.companycode='01' 
    group by 
     lpcode) todate on todate.lpcode = lp_des.lpcode 
    right join 
    (select 
     r.lpcode, 
     count(r.vehicleno) cnt_veh_tdy 
    from 
     registration r 
    where 
     r.companycode = '01' 
     and registration.date = (select max(date) from registration) 
    group by 
     r.lpcode) today on today.lpcode = lp_des.lpcode 

但我认为你的意思是这样的:

select 
    r.lpcode, 
    l.lpname, 
    count(r.vehicleno) cnt_veh_tdate, 
    count(case when r.date = md.date then r.vehicleno else null end) cnt_veh_tdy 
from 
    registration r 
    inner join (select max(rm.date) maxdate from registration rm) md 
    left join loadingpoint l on l.lpcode = r.lpcode 
where 
    r.companycode = '01' 
group by 
    r.lpcode 

,甚至这样的:

select 
    r.lpcode, 
    l.lpname, 
    count(r.vehicleno) cnt_veh_tdate, 
    count(case when r.date = date() then r.vehicleno else null end) cnt_veh_tdy 
from 
    registration r 
    left join loadingpoint l on l.lpcode = r.lpcode 
where 
    r.companycode = '01' 
group by 
    r.lpcode 

如果我正确地读它,你想有一个查询,返回分配给负载点公司1车的数量,整体以及今天只。而且您还希望计算尚未分配加载点的车辆数量。 虽然这将有所帮助,如果会添加此说明。它将帮助那些回答你的问题的人,但它也将帮助你首先编写正确的查询。

0

的SY帮助和ntax为右外连接是:

SELECT t1.id, t2.id FROM t1 RIGHT OUTER JOIN t2 ON t1.field1 = t2.field2 

如果你在同一领域你的加盟可以使用USING,而不是ON

SELECT t1.id, t2.id FROM t1 RIGHT OUTER JOIN t2 USING (field) 
+0

请接受我的查询,并在该查询中进行外部联接ur示例不起作用 – 2012-03-31 07:11:32