如何使用JOIN连接两个表

时间:2019-11-26 12:58:18

标签: mysql

能帮我如何在单个表中联接两个查询

照明明细表:

select 
    mac_id, round(sum(luminary_count::int * wattage::int)::numeric/100, 2) as rated_power 
from 
    luminary_details AS A
join 
    geo_light as gl on A.mac_id = gl.id 
group by
    A.mac_id

// lastupdated_all

select mac_id, (tactivep::numeric)
from lastupdated_all AS A
join geo_light as gl on A.mac_id = gl.id 
group by A.mac_id

1 个答案:

答案 0 :(得分:0)

您可以使用geo_ligth作为主表,并通过id = mac_id联接2查询作为子选择..

select gl.id,  t1.rated_power, t2.tactivep
from  geo_light  gl
LEFT JOIN  (
  select mac_id, round(sum(luminary_count::int * wattage::int)::numeric/100, 2) as rated_power 
  from luminary_details AS A
  join geo_light as gl on A.mac_id = gl.id 
  GROUP BY A.mac_id
)  t1 on t1.mac_id  = gl.id 
LEFT JOIN  (
  select mac_id, (tactivep::numeric) num_tactivep
  from lastupdated_all AS A
  join geo_light as gl on A.mac_id = gl.id 
  GROUP BY A.mac_id
) t2 on t2.mac_id = gl.id