内部连接不同的表,基于列值

时间:2016-11-17 11:50:51

标签: sql

请用我的选择帮助我。 我有i表载波,其中包含有关载波的信息:car_id,car_name,car_zones(此值为表名,具有此载波的区域数据),car_rates_exp(此值为表名,具有此载波的导出率数据),car_rates_imp (此值为表名,具有此运营商的导入率数据),car_href(此值为跟踪此运营商的api的href值)

我也有表'订单',在所有字段中,它有列carrier_id,from_country,weight和shipper_rate。我想做一个我想要与表进行内连接的选择,但查询中的这个表名必须不同,基于carrier_id。我试图进行此查询,但它不起作用:

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

所以字符串

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

不起作用,请你帮我解决这个问题?

1 个答案:

答案 0 :(得分:2)

子查询不包含您要加入的字段ID

o.from_country = z.id

将id添加到子查询中。