doudu2591 2013-11-12 06:09
浏览 58
已采纳

JOIN和INNER JOIN查询

NB: I have asked a question just before (How to select from the db where version field is the recent one) and it's working well. It's not the duplicate.

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

Using the above query I can select all the details from pricing table where distributor has the latest version.[Distributor will have different versions. I only need to select the latest version]. I have another table called product_picker. I only need to select the data from pricing table where code of pricing= code of product_picker. I have used the below code:

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

But I know it wouldn't work well. I am just learning the JOIN Clauses. How can I improve my code?

Thanks!

  • 写回答

1条回答 默认 最新

  • dqmg80654 2013-11-12 06:13
    关注

    The mechanism is pretty simple:

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue使用gojs,需求在link中的虚线上添加方向箭头
  • ¥15 CSS通配符清除内外边距为什么可以覆盖默认样式?
  • ¥15 SPSS分类模型实训题步骤
  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红