NB: 我刚才问了一个问题(How to select from the db where version field is the recent one)并且它运作良好。这不是重复。
SELECT p.* FROM `pricing` p
JOIN (SELECT `distributor`,MAX(`version`) AS ver
FROM `pricing` GROUP BY `distributor`) mx
ON mx.ver=p.version AND p.distributor = mx.distributor
使用上述查询,我可以从定价表中选择所有详细信息,其中分销商拥有最新版本。[分销商将有不同的版本。我只需要选择最新版本]。我有另一个名为product_picker的表。我只需要从定价表中选择数据,其中定价代码= product_picker的代码。我使用了以下代码:
SELECT p.* FROM `pricing` p,pk.*
FROM `product_picker`
JOIN (SELECT `distributor`,MAX(`version`) AS ver
FROM `pricing` GROUP BY `distributor`) mx
ON mx.ver=p.version AND p.distributor = mx.distributor
INNER JOIN `product_picker` pk ON p.code=pk.code
但我知道这不会很好。我刚刚学习了JOIN条款。如何改进我的代码?
谢谢!
答案 0 :(得分:2)
机制非常简单:
SELECT p.*, pk.*
FROM
`pricing` p
JOIN (
SELECT
`distributor`,
MAX(`version`) AS ver
FROM `pricing`
GROUP BY `distributor`
) mx ON mx.ver = p.version AND p.distributor = mx.distributor
JOIN `product_picker` pk ON pk.code = p.code -- the join has to be added after the other one, and the ON clause has to make it clear for SQL that the code is the criteria