【问题标题】:MySQL Query Optimization for two tables where ID does not exits in 2nd table对第二个表中不存在 ID 的两个表的 MySQL 查询优化
【发布时间】:2016-10-03 06:17:59
【问题描述】:

我们在 MySQL 查询下面有这个。虽然查询在具有大量数据的本地主机中顺利运行,但在实时服务器中需要大量时间。我试图优化它,但没有任何效果。这段代码可以用更简单的术语编写吗? 帮助将不胜感激。

SELECT id, Request_By, Org_Name, Branch_Name, SALES_PERSON, Is_Consignee, Is_Shipper, EmailId, Telephone, Credit_LimitRS, IE_Code_No,
    PAN_No, Credit_limitDAYS, GL_Link 
    FROM mst_ship_con_newcust
    WHERE ( not EXISTS ( SELECT * FROM mst_branch_info b where b.id = mst_ship_con_newcust.id) ) 
    ORDER BY id desc

【问题讨论】:

  • 请把解释的结果从服务器贴出来,也让我们大致知道服务器执行查询需要多长时间,以及表中有多少条记录。
  • 我得到了数据,但是在实时服务器中显示结果大约需要 3 1/2 到 4 分钟
  • 好的。请向我们展示解释的结果。在那之前,这只是一个纯粹的猜测。
  • 怎么样?请指导。我只显示第一个表的数据,其中第一个表的主 ID 不在第二个表中。
  • explain select ...

标签: mysql sql query-optimization


【解决方案1】:
SELECT id, Request_By, Org_Name, Branch_Name, SALES_PERSON, Is_Consignee,    Is_Shipper, EmailId, Telephone, Credit_LimitRS, IE_Code_No,
PAN_No, Credit_limitDAYS, GL_Link 
FROM mst_ship_con_newcust
  LEFT JOIN mst_branch_info b ON b.id = mst_ship_con_newcust.id
WHERE b.id IS NULL
ORDER BY id desc

这样的 LEFT JOIN 怎么样?

更新:

SELECT id, Request_By, Org_Name, Branch_Name, SALES_PERSON, Is_Consignee,    Is_Shipper, EmailId, Telephone, Credit_LimitRS, IE_Code_No,
PAN_No, Credit_limitDAYS, GL_Link 
FROM mst_ship_con_newcust
  JOIN mst_branch_info b ON b.id = mst_ship_con_newcust.id
ORDER BY id desc

然后加入

【讨论】:

  • 谢谢,但我想显示 mst_ship_con_newcust.id 尚未在 b.id 中退出的位置
  • LEFT 需要将输出限制为“不存在...尚未”。
【解决方案2】:

id 上连接两个表是不常见的。这种架构设计的历史是什么?

确保在两个表上都有以id 开头的索引,然后尝试

SELECT  y.id, y.Request_By, y.Org_Name, y.Branch_Name, y.SALES_PERSON,
        y.Is_Consignee, y.Is_Shipper, y.EmailId, y.Telephone,
        y.Credit_LimitRS, y.IE_Code_No, y.PAN_No, y.Credit_limitDAYS,
        y.GL_Link
    FROM  
    (
        SELECT  n.id
            FROM  mst_ship_con_newcust AS n
            LEFT JOIN  mst_branch_info AS b  ON b.id = n.id
            WHERE  b.id IS NULL 
    ) AS x
    JOIN  mst_ship_con_newcust AS y USING (id)
    ORDER BY  id desc 

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多