使用带有附加条件的EXISTS获取最大行

时间:2014-07-16 10:16:16

标签: mysql sql exists

我在MySQL数据库中有一个表weight。可以在下面的快照中查看。

weight表:

weight

我需要以下查询。

SELECT * 
FROM   weight w 
WHERE  w.weight_id IN (SELECT MAX(ww.weight_id) 
                       FROM   weight ww 
                       WHERE  ww.weight BETWEEN 0 AND 60);

语法上从weight表中weight列的值介于0和60之间的行中获取最大行(例如)。


我希望使用EXISTS()进行相同的查询。以下尝试不成功。

SELECT * 
FROM   weight w 
WHERE  NOT EXISTS (SELECT 1 
               FROM   weight ww 
               WHERE  w.weight_id < ww.weight_id 
                      AND ww.weight BETWEEN 0 AND 60);

它返回从最大行开始的所有行(如果省略BETWEEN条件(AND ww.weight BETWEEN 0 AND 60)然后,它从表中的所有行返回最大值,但它是不希望的。它应该是根据{{​​1}}条件应用过滤器后返回最大行。

略微修改后的版本不会返回任何行。

BETWEEN

我还可以选择使用SELECT * FROM weight w WHERE EXISTS (SELECT 1 FROM weight ww WHERE w.weight_id = ww.weight_id AND ww.weight BETWEEN 0 AND 60 AND NOT EXISTS(SELECT 1 FROM weight www WHERE ww.weight_id < www.weight_id)) 吗?

我正在使用ORM框架,EXISTS()子句中不支持子查询。因此,如果FROM中的子查询被排除,那将会好得多。

1 个答案:

答案 0 :(得分:0)

一般来说,id只能用作行标识符,而不能使用MAX()进行比较。

如果您希望在两个值之间具有最大weight的行:

  SELECT id, weight
    FROM weight
   WHERE weight BETWEEN 0 AND 60
ORDER BY weight DESC
   LIMIT 1

在这种情况下,我不会使用EXISTS

<强>更新

如果您无法使用LIMIT,那么:

  SELECT id, weight
    FROM weight
   WHERE weight = (
    SELECT MAX(wi.weight)
      FROM weight wi 
     WHERE wi.weight BETWEEN 0 AND 60
         )
如果MAX(weight)

没有欺骗,

将返回相同的内容

如果您坚持使用EXISTS,那么您可以尝试:

 SELECT * 
   FROM weight w 
  WHERE NOT EXISTS (
   SELECT 1 
     FROM weight ww 
    WHERE w.weight < ww.weight 
      AND ww.weight BETWEEN 0 AND 60
        )
    AND w.weight BETWEEN 0 AND 60