简体   繁体   English

PostgreSQL,与众不同,按排序和括号

[英]PostgreSQL, distinct, order by and parentheses

I have the following request: 我有以下要求:

select distinct m1.firstname, m1.surname 
  from cd.members as m1 
  join cd.members as m2 on m2.recommendedby = m1.memid 
  order by m1.surname, m1.firstname;

and it works fine. 而且效果很好。 But this one: 但是这个:

select distinct m1.firstname, m1.surname 
  from cd.members as m1 
  join cd.members as m2 on m2.recommendedby = m1.memid 
  order by (m1.surname, m1.firstname);

gives me the error: 给我错误:

ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list

I can't understand when I have to use parentheses and when not. 我不明白什么时候必须使用括号,什么时候不用。

Postgres has the concept of tuples or composite types . Postgres具有元组复合类型的概念。 These are scalar values that appear together -- much like a record or struct in many programming languages. 这些是标量值,它们一起出现-很像许多编程语言中的记录或结构。

You can use tuples for expressions, such as: 您可以将元组用于表达式,例如:

where (m1.surname, m1.firstname) in ( ('a', 'b'), ('x', 'y') )

The problem with your order by expression is that the tuple is not in the select . order by表达式order by问题是元组不在select You could solve this by using parentheses there too: 也可以在此处使用括号解决此问题:

select distinct (m1.firstname, m1.surname)
from cd.members m1 join
     cd.members m2
     on m2.recommendedby = m1.memid 
order by (m1.surname, m1.firstname);

But I would stick with the parentheses-less version, which is standard SQL and works in all databases. 但是我会坚持使用无括号的版本,该版本是标准SQL,适用于所有数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM