外部加入mYsql查询

时间:2012-03-31 06:37:29

标签: mysql outer-join

我有以下MYsql查询和尝试右外连接但无法理解如何执行此操作

这里是查询任何一个帮助

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

请提前帮助并提前致谢

2 个答案:

答案 0 :(得分:0)

右外连接的语法是:

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)

答案 1 :(得分: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的车辆数量,总体上和仅今天。并且您还希望计算尚未分配装载点的车辆。 虽然如果会添加这个描述会有所帮助。它将帮助那些回答您问题的人,但它也可以帮助您首先编写正确的查询。