使用前缀和组合

时间:2016-02-16 14:30:50

标签: mysql join group-by

我有三个mysql表已经实现从订单表中获得所有发票以及Invoice_No_Amt - Refund_Amount,结算价值的组合总和

现在我想让sku_mapping表中的fullname列也列在结果中。 prefix_sku是sku_mapping表中的主键

fk_orders

|order_item_id |order_id    |Invoice_No       |Invoice_No_Amt  |Qty   |Refund_Qty |Refund_Amount | sku
------------------------------------------------------------------------------------------------------
|1131231       |123         |F08OTTN16-1      |100            |1     |            |              |A3001
|1113138       |321         |F08OTTN16-2      |200            |2     |1           |200           |B1001
|1231231       |023         |F08OTTN16-3      |100            |1     |1           |100           |C2001
|1133138       |320         |F08OTTN16-4      |200            |2     |            |              |D8901
|1134231       |103         |F08OTTN16-5      |100            |1     |            |              |E6210
|1113538       |300         |F08OTTN16-6      |200            |2     |            |              |F1001
|1003538       |300         |F08OTTN16-7      |200            |2     |            |              |G9003

fk_payments

|order_item_id    |order_id    |Invoice_No       |Invoice_No_Amt |Settlement Value
-----------------------------------------------------------------------------------
|OI:1131231       |123         |F08OTTN16-1      |100            |40
|OI:1113138       |321         |F08OTTN16-2      |200            |150
|OI:1231231       |023         |F08OTTN16-3      |100            |-50
|OI:1133138       |320         |F08OTTN16-4      |200            |200
|OI:1134231       |103         |F08OTTN16-5      |100            |40
|OI:1113538       |300         |F08OTTN16-6      |200            |250
|OI:1131231       |123         |F08OTTN16-1      |100            |40
|OI:1133138       |320         |F08OTTN16-4      |200            |100
|OI:1113138       |321         |F08OTTN16-2      |200            |-200

sku_mapping

|prefix_sku |full_name 
-------------------
f|A3001     |Apple_Phone
f|B1001     |Belkin
f|C2001     |Cat_Access
f|D8901     |Dlink
f|E6210     |Eltron
f|F1001     |Flag
f|G9003     |gott
a|A3001     |Apple_Phone
a|B1001     |Belkin
a|C2001     |Cat_Access
a|D8901     |Dlink
a|E6210     |Eltron
a|F1001     |Flag
a|G9003     |gott

查询

select o.*,
       (coalesce(Refund_Amount, 0) + coalesce(sv, 0)) as SettledAmount,
       (Invoice_No_Amt - coalesce(Refund_Amount, 0) - coalesce(sv, 0)) as netAmount
from fk_orders o left join
     (select invoice_no, sum(Settlement_Value) as sv
      from fk_payments
      group by invoice_no
     ) p
     on o.invoice_no = p.invoice_no;

猜测这个声明是否包含在上面的代码中以从sku_mapping表中获取prefix_sku但是如何在join中使用where语句

concat('f |',O。f|sku)= conso.conso

1 个答案:

答案 0 :(得分:0)

所以如果你想添加" where条件"在连接中,您可以通过指定连接条件来执行此操作,例如

select * 
from A 
join B 
  on A.id = B.id 
 and B.id > 4000 ;