Changing this query to group rows and filter out all rows apart from the one with smallest value

丶灬走出姿态 提交于 2019-12-23 04:34:42

问题


I have the following results set:

275     72.87368055555555555555555555555555555556   foo
275     72.87390046296296296296296296296296296296   foo
113     77.06431712962962962962962962962962962963   foo
113     77.07185185185185185185185185185185185185   foo

that I got from this query:

SELECT id, (tbl2.date_modified - tbl1.date_submitted)/86400, some_value
FROM tbl1, tbl2, tbl3
WHERE tbl1.id = tbl2.fid 
AND tbl1.id = tbl3.fid

How can I change it to get this:

275     72.87368055555555555555555555555555555556   foo
113     77.06431712962962962962962962962962962963   foo

i.e. get only the row with the smallest some_number

Sub queries or something ?

Many thanks :).


回答1:


if some_value is a field name :

SELECT id, min((tbl2.date_modified - tbl1.date_submitted)/86400), max(some_value)
FROM tbl1, tbl2, tbl3
WHERE tbl1.id = tbl2.fid 
AND tbl1.id = tbl3.fid
GROUP BY tbl1.id

if some_value is a some constant string :

SELECT id, min((tbl2.date_modified - tbl1.date_submitted)/86400), 'some_value'
FROM tbl1, tbl2, tbl3
WHERE tbl1.id = tbl2.fid 
AND tbl1.id = tbl3.fid
GROUP BY tbl1.id



回答2:


You can wrap this in a subquery:

SELECT x.id,
  min(result),
  x.some_value
FROM
(
  SELECT id, 
    (tbl2.date_modified - tbl1.date_submitted)/86400 result, 
    some_value
  FROM tbl1, tbl2, tbl3
  WHERE tbl1.id = tbl2.fid 
    AND tbl1.id = tbl3.fid
) x
group by x.id, x.some_value

Just as a suggestion, I might rewrite the query to use ANSI join syntax instead of commas between the tables, similar to this:

SELECT x.id,
  min(result),
  x.some_value
FROM
(
  SELECT id, 
    (tbl2.date_modified - tbl1.date_submitted)/86400 result, 
    some_value
  FROM tbl1
  INNER JOIN tbl2
    ON tbl1.id = tbl2.fid
  INNER JOIN tbl3
     ON tbl1.id = tbl3.fid
) x
group by x.id, x.some_value

Or you can add the MIN() function to your original without a subquery and add a GROUP BY

  SELECT id, 
    MIN((tbl2.date_modified - tbl1.date_submitted)/86400) result, 
    some_value
  FROM tbl1, tbl2, tbl3
  WHERE tbl1.id = tbl2.fid 
    AND tbl1.id = tbl3.fid
  GROUP BY id, some_value


来源:https://stackoverflow.com/questions/12331810/changing-this-query-to-group-rows-and-filter-out-all-rows-apart-from-the-one-wit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!