1

I need to fetch distinct values of a table, which has an auto-incremented id field. I need the id to identify, but I don't care which id when all values are the same except the id.

I came up with the following, which seems to work. Is there a better way to do this though?

SELECT id, date_f, date_t, num_n, num_d, mn, is 
FROM t
GROUP BY date_f, date_t, num_n, num_d, mn, is

Another concern is, would this always return the same ids if the query is executed more than once?

EDIT:

Sample db:

id date_f date_t num_n num_d mn is
1   10      10      10  10   10 10
2   10      10      10  10   10 10
3   10      10      10  10   10 10

I want to store all of the columns of one row out of these. I don't care if the id is 1, 2 or 3 as long as it's the same the next time I execute the query (without adding/deleting any rows between). So far, two answers suggested using min(id) which seems like a good idea.

4

3 回答 3

2

如果您根本没有在结果集中使用 id,那么上面的答案就可以了。如果您出于任何目的需要在结果集中至少有一个 Id,那么您应该稍微更改您的语句:

SELECT min(id), date_f, date_t, num_n, num_d, mn, is 
FROM t
GROUP BY date_f, date_t, num_n, num_d, mn, is

这将返回与不同集匹配的第一个 Id(或者如果您想要最后一个,则使用 (Max) - 这可能会随着时间的推移而改变,尽管随着数据被添加到表中。

于 2013-11-07T13:49:02.270 回答
1

你所拥有的基本上是正确的 - 我会补充说,如果你想要 id (身份),那么你需要添加一个聚合,例如 -

SELECT min(id), date_f, date_t, num_n, num_d, mn, is 
FROM t
GROUP BY date_f, date_t, num_n, num_d, mn, is

这将确保您每次都获得第一个/相同的(当然,除非它被删除)

于 2013-11-07T13:49:56.297 回答
0

SELECT DISTINCT date_f, date_t, num_n, num_d, mn, is FROM t

于 2013-11-07T13:43:54.917 回答