sql >> Base de Datos >  >> RDS >> Mysql

unir dos tablas sin perder valores relevantes

Creo que estás buscando esto:

select distinct *
from (SELECT date,
             if(group_concat(distinct cust_price), from_product_id, null)as from_product_id,
             if(group_concat(distinct comp_price), to_product_id, null)  as to_product_id,
             group_concat(distinct cust_price)                           as cust_price,
             group_concat(distinct comp_price)                           as comp_price
      FROM (select cust_hist.date,matches.from_product_id,
                   matches.to_product_id,cust_hist.price cust_price,
                   comp_hist.price                       comp_price
            from tmp_match matches
                   inner join tmp_price_history cust_hist on matches.from_product_id = cust_hist.product_id
                   inner join tmp_price_history comp_hist on matches.to_product_id = comp_hist.product_id
            WHERE comp_hist.date = cust_hist.date
            union
            select comp_hist.date,matches.from_product_id,
                   matches.to_product_id,null as cust_price,
                   comp_hist.price               comp_price
            from tmp_price_history comp_hist
                   join tmp_match matches
                     on matches.to_product_id = comp_hist.product_id # and matches.from_product_id is null

            union
            select cust_hist.date,matches.from_product_id,
                   matches.to_product_id,
                   cust_hist.price cust_price,
                   null            comp_price
            from tmp_price_history cust_hist
                   join tmp_match matches
                     on matches.from_product_id = cust_hist.product_id # and matches.to_product_id is null

            order by DATE, from_product_id, to_product_id, cust_price, comp_price) as u
      group by date,from_product_id,to_product_id) g

¡Tu idea sobre el fragmento de sql fue genial!