简体   繁体   中英

inner join different tables, based on column value

Help me please with my select. I have i table carriers, which contains information about carrier: car_id, car_name, car_zones (this value is table name, which has this carrier's zones data), car_rates_exp (this value is table name, which has this carrier's export rates data), car_rates_imp (this value is table name, which has this carrier's import rates data), car_href (this value is href to tracking api of this carrier)

Also I have table 'orders', among all fields, it has column carrier_id, from_country, weight and shipper_rate. I want to make a select in which I want to make inner join with table, but this table name in query has to be different, based in carrier_id. I tried to make this query, but it does not work:

SELECT o.id_order, 
       o.from_country, 
       c.firstname, 
       c.lastname, 
       o.carrier_id, 
       ot.name as order_type, 
       z.Zone_name, 
       cr.car_zones, 
       cr.car_name, 
       cr.car_href, 
       o.invoice_amount,  
       o.rated_weight, 
       o.shipping_rate, 
       o.shipping_rate_my_fee, 
       o.customs_tax, 
       o.customs_tax_2, 
       o.customs_my_fee, 
       o.total_shipping_fee, 
       o.total_my_costs, 
       o.1kg_price, 
       o.my_profit, 
       o.goods_for_ship, 
       o.waybill,  
       o.prev_DHL_fee, 
       o.customer_paid, 
       os.name as order_status, 
       os.color 
FROM orders o 
  inner join customer c on o.id_customer = c.id 
  inner join order_types on on o.order_type = ot.id 
  inner join (select car_zones 
              from   carriers 
              where  car_id=o.carrier_id) z on o.from_country = z.id 
  inner join carriers cr on IF(o.carrier_id = 0, 1, o.carrier_id) = cr.car_id
  inner join order_status os on o.order_status = os.id
where import_or_export = 'import' AND o.active > 0

So the string

inner join (select car_zones from carriers where car_id=o.carrier_id) z on o.from_country = z.id 

does not work, can you please help me to solve this situation?

The subquery doesn't contain a field id to which you are joining to

o.from_country = z.id

Add the id to the subquery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM