优化具有最大功能的查询

时间:2011-06-24 20:13:57

标签: sql performance hibernate optimization

我想从表中选择一行,其中包含一些条件和一些参数 x 的最大值(这是字符串)。我现在正在做:

SELECT FROM myTable mm
WHERE       mm.userId = :userId
  AND       x = (
              SELECT MAX(x)
              FROM   myTable m
              WHERE  m.userId = :userId
                AND  (m.to = :contactNumber OR m.from = :contactNumber)
                AND       ...
            )

我不确定ll inno db如何执行此查询,但需要帮助来改进此查询。我正在使用休眠。

3 个答案:

答案 0 :(得分:1)

    SELECT TOP 1 * FROM myTable m
      WHERE m.userId = :userId
      AND  (m.to = :contactNumber OR m.from = :contactNumber)
      AND       ...
      ORDER BY m.x DESC

答案 1 :(得分:0)

类似于C.Zonnenberg的回答,但对于MySQL:

SELECT * FROM myTable
WHERE userId = :userId
AND  (m.to = :contactNumber OR m.from = :contactNumber)
...
ORDER BY x DESC
LIMIT 1

答案 2 :(得分:0)

SELECT mm.*
FROM myTable mm
  LEFT JOIN myTable m
    ON mm.UserId = m.UserId
   AND (m.to = :contactNumber OR m.from = :contactNumber)
   AND mm.x < m.x
WHERE mm.userId = :userId
  AND (mm.to = :contactNumber OR mm.from = :contactNumber)
  AND m.userId IS NULL

这使用一种已知技术,使用LEFT JOIN to self来查找最大值或最小值。基本上这种技术是这样的:

 SELECT a.*
 FROM a
   LEFT JOIN a AS a2 ON a.key = a2.key AND a.value < a2.value
 WHERE a2.key IS NULL

这将返回a的所有行,每个value的最大值为key。对于最低要求,您基本上将<替换为>