Django 创建的 SELECT DISTINCT、ORDER BY 适用于 MySQL 和 SQLite,不适用于 PostgreSQL
我刚刚从 mysql 切换到 postgres (耶!),但现在在我的 postgres 服务器上(仅)我收到一个错误:
SELECT DISTINCT, ORDER BY 表达式必须出现在选择列表中
这是相同的查询:
SELECT DISTINCT * FROM table ORDER BY '?'
顺便说一句,这是一个查询自动-由 django 生成。或者,有什么方法可以让 django 真正渲染正确的 sql?
附录 事实
证明,无论出于何种原因,在我的 Postgres 8.4 生产服务器上,Django 消除了错误,而在我的 Postgres 9.0 开发服务器上则不然。我不知道它是否与 Postgres 版本有关,但实际上在 Postgreses 中都出错,而不是在 MySQL 中。
I just switched from mysql to postgres (yay!) but now on my postgres server (only) I'm getting an error that:
SELECT DISTINCT, ORDER BY expressions must appear in select list
It's the same query:
SELECT DISTINCT * FROM table ORDER BY '?'
BTW this is a query auto-generated by django. Alternatively, any way to get django to actually render correct sql?
Addendum
It turns out that for whatever reason, with my Postgres 8.4 production server, Django was quashing the error, while with my Postgres 9.0 dev server it was not. I have no idea if it was related to the Postgres versions or not, but it WAS in fact erroring in both Postgreses and NOT in MySQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我预计所有符合 SQL 标准的 SQL 平台都会引发类似的错误。
这样想吧。
现在想想下一句话的含义。
dbms 应使用哪个值“c”来在排序顺序中定位“id”1?如果选择“a”,则顺序为“1,2”。如果选择“z”,则顺序为“2,1”。
I'd expect all SQL platforms that comply with SQL standards to raise a similar error.
Think about it this way.
Now think about what this next statement means.
Which value of 'c' should the dbms use to position 'id' 1 in the sort order? If it chooses 'a', the order is '1,2'. If it chooses 'z', the order is '2,1'.
作为 @Catcall 说,从技术上讲,这个语句在 SQL 中是非法且无意义的。
但是,MySQL 和 SQLite 允许您执行
SELECT DISTINCT id FROM test ORDER BY无论什么
,而 PostgreSQL 则不允许。就这么简单。MySQL 和 SQLite 可能会使用这种方法产生不确定的结果,我不确定。
但是,如果您通过
'?'
订购,应该没问题。As @Catcall said, technically this statement is illegal and nonsensical in SQL.
However, MySQL and SQLite allow you to do a
SELECT DISTINCT id FROM test ORDER BY whatever
, while PostgreSQL does not. It's as simple as that.MySQL and SQLite may produce non-deterministic results using this method, I'm not sure.
However if you are ordering by
'?'
, it should be fine.