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 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 android报错 brut.common.BrutException: could not exec (exit code = 1)
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!