使用 DISTINCT 时 SQLite 结果乱序
我有一个 SQLite 查询,其中按日期对结果进行排序。这很好用。但是,当我在 SQL 语句中引入“DISTINCT”时,结果不再保持顺序。
有什么想法吗?
SELECT date
FROM details
ORDER BY date(date); // Results are ordered correctly
April 04, 2011
April 04, 2011
April 04, 2011
April 03, 2011
April 01, 2011
March 25, 2011
SELECT DISTINCT date
FROM details
ORDER BY date(date); // Results are out of order
April 01, 2011
April 03, 2011
April 04, 2011
March 25, 2011
I have an SQLite query in which I am ordering the results by date. This works fine. However, when I introduce "DISTINCT" into the SQL statement, the results no longer stay in order.
Any thoughts?
SELECT date
FROM details
ORDER BY date(date); // Results are ordered correctly
April 04, 2011
April 04, 2011
April 04, 2011
April 03, 2011
April 01, 2011
March 25, 2011
SELECT DISTINCT date
FROM details
ORDER BY date(date); // Results are out of order
April 01, 2011
April 03, 2011
April 04, 2011
March 25, 2011
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
date()
函数无法识别您的date
列,因此date(date)
给出NULL
。使用
ORDER BY NULL
尝试这两个查询,您将获得与ORDER BY date(date)
相同的结果,如果没有
DISTINCT
,它将通过插入对它们进行排序命令。对于
DISTINCT
,顺序来自DISTINCT
本身,并应用于date
列,该列是文本,因此按字母顺序排列。SQLite 不支持月份名称。将数据更改为支持的格式(请参阅日期和时间函数)或将日期列转换为可识别的格式,然后将其提供给
date()
(使用字符串函数)例如(将
date
转换为格式YYYY-mmm-dd< /code> 调用之前
date()
有效):(此处
CASE WHEN
仅限于您的数据,您可以将其扩展到所有月份),将给出正确的带或不带
DISTINCT
的结果。Your
date
column is not in recognized by thedate()
function, sodate(date)
givesNULL
.Try both queries with
ORDER BY NULL
you'll have the same results as withORDER BY date(date)
Without
DISTINCT
it's ordering them by insert order.With
DISTINCT
, the order comes fromDISTINCT
itself and is applied to thedate
column which is a text so it's in alphabetic order.SQLite does not support month names. Change your data to supported formats (see Date And Time Functions) or transform the date column to recognized format before giving it to
date()
(with string functions)For example (transforming
date
to the formatYYYY-mmm-dd
before callingdate()
works):(here
CASE WHEN
is limited to your data, you can extend it to all months), will give the correct results with or without
DISTINCT
.我认为您的日期字符串不是有效的日期格式。
尝试运行此 SQL 看看您会得到什么:
如果出现错误,则说明它没有正确解析您的日期。
您的第二个查询按字母顺序返回,而不是按时间顺序返回 - 如果它不是该字段中的有效日期,这就是原因。
I don't think your date string is in a valid date format.
Try running this SQL to see what you get:
If you get errors, it is not parsing your dates correctly.
Your second query is returning in alphabetic order, not chronological order - if it is not a valid date in that field, that would be the reason.