1

我有以下结果集:

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

我从这个查询中得到:

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

我怎样才能改变它来得到这个:

275     72.87368055555555555555555555555555555556   foo
113     77.06431712962962962962962962962962962963   foo

只得到最小的行 some_number

子查询什么的?

非常感谢 :)。

4

2 回答 2

3

如果some_value是字段名称:

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

ifsome_value是一个常量字符串:

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
于 2012-09-08T15:00:18.520 回答
0

您可以将其包装在子查询中:

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

作为一个建议,我可能会重写查询以使用 ANSI 连接语法而不是表之间的逗号,类似于:

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

或者,您可以在MIN()没有子查询的情况下将函数添加到原始函数并添加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
于 2012-09-08T15:10:43.730 回答