0

注意:我之前问过一个问题(如何从版本字段是最新版本的数据库中选择)并且它运行良好。这不是副本。

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 子句。如何改进我的代码?

谢谢!

4

1 回答 1

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
于 2013-11-12T06:13:08.610 回答