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

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题