MySQL通过优化选择distinct或group

时间:2017-06-15 15:14:54

标签: mysql sql select distinct

我遇到从查询中获取唯一结果的问题。 Detail表有800K行,Matrix表有988K行。有索引,但要么我没有设置正确的索引,要么它们不能与查询一起使用。说明细节表没有可能的键。 Matrix显示可能的键,但键值为NULL,Extra表示:

Using where; Using join buffer (flat, BNL join)

查询:

SELECT
  Detail.Geocode AS Geocode,
  Detail.Taxtype AS Taxtype,
  Detail.TaxCat AS TaxCat,
  Detail.TaxAuthId AS TaxAuthId,
  Detail.TaxRate AS TaxRate,
  Detail.Fee AS Fee,
  Matrix.`Group` AS `Group`,
  Matrix.Item AS Item,
  Matrix.Customer AS Customer
FROM Detail
  LEFT OUTER JOIN Matrix
    ON Detail.Taxtype = Matrix.TaxType
    AND Detail.TaxCat = Matrix.TaxCat
    AND Detail.Geocode = Matrix.Geocode
    OR Matrix.Geocode = CONCAT(SUBSTR(Detail.Geocode, 1, 4), '00000000')
    AND Matrix.TaxAuthId = Detail.TaxAuthId
    OR ISNULL(Matrix.TaxAuthId)

执行上述查询即可完成,但会产生大量重复项。考虑到我正在使用的数据,我期待这一点。

我尝试过使用DISTINCT和GROUP BY,但它永远不会完成。

E.g

GROUP BY Detail.Geocode,
         Detail.Taxtype,
         Detail.TaxCat,
         Detail.TaxAuthId,
         Detail.TaxRate,
         Detail.Fee,
         Matrix.`Group`,
         Matrix.Item,
         Matrix.Customer

我已经看到一些DISTINCT放在连接中的示例,但我无法弄清楚如何使用我的查询正确执行此操作。

1 个答案:

答案 0 :(得分:0)

问题在于()。谢谢xQbert!

SELECT
  Detail.Geocode AS Geocode,
  Detail.Taxtype AS Taxtype,
  Detail.TaxCat AS TaxCat,
  Detail.TaxAuthId AS TaxAuthId,
  Detail.TaxRate AS TaxRate,
  Detail.Fee AS Fee,
  Matrix.`Group` AS `Group`,
  Matrix.Item AS Item,
  Matrix.Customer AS Customer
FROM Detail
  LEFT OUTER JOIN Matrix
    ON Detail.Taxtype = Matrix.TaxType
    AND Detail.TaxCat = Matrix.TaxCat
    AND (Detail.Geocode = Matrix.Geocode
    OR Matrix.Geocode = CONCAT(SUBSTR(Detail.Geocode, 1, 4), '00000000'))
    AND (Matrix.TaxAuthId = Detail.TaxAuthId
    OR ISNULL(Matrix.TaxAuthId))