2012-03-31 56 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