问题
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