我有3张桌子,如下所示:

产品表

PID       CODE
1        a
2        b


价格表

PrID    PID(ID from Product)   UMID(ID from UOM)  Price
1         1                        1               10
2         1                        2                5
3         2                        1               10


UOM表

UMID           UM_NAME         UM_RATE
1               BOX              5
2               PC               10


我想使用product来获取price,并且该min至少为uomUM_RATE。例如,产品CODE a具有两个价格,但是不同的uom的价格是不同的。我想要实现的是

PID     CODE    PrID    Price     UM_NAME     UM_RATE
1        a       1       10         BOX          5
2        b       3       10         BOX         5


因为box具有min UM_RATE。我已经尝试过以下查询,

SELECT product.*, price.*, uom.um_name, MIN(uom.um_rate)
FROM product
LEFT JOIN price ON price.pid = product.pid
LEFT JOIN uom ON price.umid = uom.umid
GROUP BY product.pid


这个查询给我以下结果,

PID     CODE    PrID    Price     UM_NAME     UM_RATE
1        a       1       10         PC          5
2        b       3       10         BOX         5


这是错误的。因为UM_RATE 5属于UM_NAME框。
如何获得预期的结果?

最佳答案

使用联接和相关子查询

    select * from (select distinct p.*,u.UMID as uid,
 u.UM_NAME,u.UM_RATE,pr.code from
 price p join uom  u on p.UMID=u.UMID
  join product pr on pr.PID=p.PID
  ) a
  where a.UM_RATE =(select min(UM_RATE) from
                    (select  p.*,u.UMID as uid,
 u.UM_NAME,u.UM_RATE,pr.code from
 price p join uom  u on p.UMID=u.UMID
  join product pr on pr.PID=p.PID) t where t.code=a.code

      )


prid    PID     UMID    price   uid     UM_NAME     UM_RATE     code
1       1       1       10      1       Box           5          a
3       2       1       10      1       Box           5          b

10-05 23:07